简体   繁体   English

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

[英]How to read a file line-by-line into a vector and then print the vector

I'm trying to read in a file, add each line into a vector, and then print the vector.我正在尝试读取一个文件,将每一行添加到一个向量中,然后打印该向量。 But right now, it will only print the first line.但现在,它只会打印第一行。 Because of this, I'm assuming that the first line is the only line being added to the vector, but I can't figure out why.因此,我假设第一行是唯一添加到向量中的行,但我不知道为什么。

Here is my code:这是我的代码:

#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) << ' ';
        }
    }
}

Here is the text file, and right now it should print out exactly as it appears here:这是文本文件,现在它应该完全按照此处显示的方式打印出来:

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

There is logic inside of your reading loop that really belongs after the loop has finished instead:在循环完成之后,您的阅读循环内部有真正属于的逻辑:

  • You are close() 'ing the file stream after the 1st line is read, thus breaking the loop after the 1st iteration.在读取第一行之后,您正在close()文件 stream ,从而在第一次迭代后中断循环。

  • You are printing the entire vector after adding each line to it.在将每一行添加到它之后,您正在打印整个vector

Also, you don't need the newLine variables at all.此外,您根本不需要newLine变量。

Try this instead:试试这个:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM