在 c++ 中逐行读取文本文件

Reading text file line by line in c++

本文关键字:取文本 文件 读取 逐行 c++      更新时间:2023-10-16

我想将文本文件中的文本读取到我的 c++ 代码中。这是我的代码:-

f.open(input);
if (f)
{   
    while(!f.eof())
    {
        LinkedList obj;
        string c, d, l;
        f>>c>>d>>l;
        nodes.push_back(c);
        nodes.push_back(d);
        vector<string> temp;
        temp.push_back(c);
        temp.push_back(d);
        temp.push_back(l);
        vecNodes.push_back(temp);
    }
 }

我的文本文件如下:

a b c
a c
d e
e
g h a

我的问题是我如何一次阅读一行。 当我的代码读取第二行时,它也读取了第三行的第一个字符,这是错误的。我知道我可以在每行的末尾放置分隔符,这可能有效。还有其他方法可以做到这一点吗?

您可以使用以下代码逐行读取文件:

string line;
ifstream myfile;
myfile.open("myfile.txt");
if(!myfile.is_open()) {
    perror("Error open");
    exit(EXIT_FAILURE);
}
while(getline(myfile, line)) {
    // do things here
}

然后按空格拆分字符串并将元素添加到列表中。