如何逐行将文件读取为向量,然后打印该向量

问题描述 投票:-1回答:1

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

这是我的代码:

#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
c++ file file-io fileinputstream
1个回答
0
投票

您的阅读循环中有逻辑inside确实属于after循环已完成:

  • [您正在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;
}
© www.soinside.com 2019 - 2024. All rights reserved.