在 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
}
然后按空格拆分字符串并将元素添加到列表中。
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 从二进制文件中抓取文本时,为什么 xdg_vtnr=8 是我的结果
- Windows XP在C++中启动时读取文本文件的速度较慢;预取