如何将文件逐行读入向量,然后打印向量

我正在尝试读取文件,将每一行添加到向量中,然后打印向量。  但是现在,它只会打印第一行。因此,我假设第一行是添加到向量中的唯一行,但是我不知道为什么。

这是我的代码:

#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
nmwangyu 回答:如何将文件逐行读入向量,然后打印向量

您的阅读循环中有内逻辑 真正属于 循环完成后

  • 在读取第一行之后,您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; } 变量。

尝试以下方法:

{{1}}
本文链接:https://www.f2er.com/3126748.html

大家都在问