如何将文件逐行读取到矢量中,然后打印矢量



我正在尝试读取文件,将每一行添加到一个向量中,然后打印向量。 但是现在,它只会打印第一行。因此,我假设第一行是添加到向量中的唯一行,但我无法弄清楚原因。

这是我的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
std::vector<std::string> vecOfStrs;
std::ifstream fileIn("example.txt");
std::string str;
std::string newLine;
newLine = str + "n";
while (std::getline(fileIn, str)) {
std::string newLine;
newLine = str + "n";
if (newLine.size() > 0) {
vecOfStrs.push_back(newLine);
}
fileIn.close();
for (int i = 0; i < vecOfStrs.size(); i++) {
std::cout << vecOfStrs.at(i) << ' ';
}
}
}

这是文本文件,现在它应该完全按照此处显示的方式打印出来:

Barry Sanders
1516 1319 1108 1875 -999
Emmitt Smith
1892 1333 1739 1922 1913 1733 -999
Walter Payton
1999 1827 1725 1677 -999

读取循环内部有一些逻辑真正属于循环完成后:

  • 您在读取第一行后close()文件流,从而在第一次迭代后中断循环。

  • 每行添加到vector后,您将打印整个。

此外,您根本不需要newLine变量。

试试这个:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main() {
std::vector<std::string> vecOfStrs;
std::ifstream fileIn("example.txt");
std::string str;
while (std::getline(fileIn, str)) {
if (str.size() > 0) {
vecOfStrs.push_back(str);
}
}
fileIn.close();
for (size_t i = 0; i < vecOfStrs.size(); i++) {
std::cout << vecOfStrs[i] << ' ';
}
return 0;
}

最新更新