逐行读取txt
Reading txt line by line
我正在C++中逐行读取一个文本文件。我使用的是这个代码:
while (inFile)
{
getline(inFile,oneLine);
}
这是一个文本文件:
-------
This file is a test to see
how we can reverse the words
on one line.
Let's see how it works.
Here's a long one with a quote from The Autumn of the Patriarch. Let's see if I can say it all in one breath and if your program can read it all at once:
Another line at the end just to test.
-------
问题是,我只能阅读以"这是一个很长的等等…"开头的段落,而它的结尾是"立刻:"我无法解决阅读所有文本的问题。你有什么建议吗?
正确的换行习惯用法是:
std::ifstream infile("thefile.txt");
for (std::string line; std::getline(infile, line); )
{
// process "line"
}
或者不喜欢for
循环的人的替代方案:
{
std::string line;
while (std::getline(infile, line))
{
// process "line"
}
}
请注意,即使无法打开文件,这也能正常工作,尽管如果您想为该情况生成专用诊断,您可能需要在顶部添加一个额外的检查if (infile)
。
相关文章:
- 一种在C++中读取TXT配置文件的简单方法
- Arduino从Txt读取整数
- Visual Studio在尝试读取resource.txt文件时崩溃
- 如何从txt文件中读取多个不同长度的数组?
- 在一次迭代中从 txt 文件中读取多行
- 我可以读取静态对象中的文件.txt吗?C++
- 在Cmake构建CmakeList.txt中读取/解析XML文件
- 从.txt文件中读取浮点型数字并在公式中使用它们
- 为什么我无法打开/读取从 Python 调用的 C 扩展名中的 txt 文件?
- 如何使用c ++读取带有非英文字母的*.txt文件?(国际化)
- 如何将变量从 CMakeLists.txt 读取到 cpp 文件
- 尝试从 txt 读取数据
- C++,从 txt 读取到矢量的双倍,读取整个文件时出现问题
- 编写一个C++ pgm 以从文件"input.txt"读取,每当遇到句点时插入换行符并将修改的内容写入"output.txt"
- C++从 txt 读取数字,直到换线(逻辑回归)
- 使用 2D 矢量从 txt 读取文件
- C++从.txt读取浮点值,并将它们放入未知大小的 2D 数组中
- 从文件.txt读取字符串数组并使用它来玩康威的生命游戏
- 从.txt [c++]读取代码
- 从.txt读取int,将其保存到vector,然后保存到输出文件