繁体   English   中英

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

[英]Reading text file line by line in c++

我想从文本文件中读取文本到我的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
}

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

暂无
暂无

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

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