如何在C 中逐行读取文本
how to read a text line by line in c++
我试图按C 的行读取文本,这是成功的。唯一的问题是,我希望用户按键盘上的" Enter"键,以读取除第一个以外的每行。我的代码有效,但前两行总是立即打印出同一行。例如,用户输入" brands.txt"作为文件的名称,并打印以下内容。
samsungapple
东芝
Acer
而不是:
三星
苹果
东芝
Acer
这可能是编译器错误,还是我的代码错误?这是我的代码:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream myFile;
string textFile;
string line;
string::size_type ext;
int count = 0;
// request and obtain the name of the text file
cout << "Enter the name of the file including the '.txt' extension: ";
cin >> textFile;
myFile.open(textFile.c_str()); // open the file
if(myFile.is_open()) // checks if the file is open and ready to be accessed
{
while(getline(myFile, line))
{
cout << line;
count += 1;
cin.get();
}
}
myFile.close();
return 0;
}
进行cin >> textFile
时,您可能会输入文本文件的名称,然后按Enter。cin
的提取操作员在流中留下了新线路。从文档中:
如果满足以下条件之一,则提取停止:
发现了一个空格字符(由ctype facet确定)。未提取Whitespace字符。
...
(强调矿山)
因此,当您进入循环并运行cin.get()
时,它会得到剩下的新线。
由于您没有在line
之后输出任何内容(如newline),因此单词看起来像这样。
解决方案可能是在进入循环之前一次在cin
上运行getline
,以确保清除所有用户输入(getline
将食用尾随的空间),即:getline(cin, junk)
相关文章:
- 如何在c++中从文本文件中逐行读取整数
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 使用 QT 逐行读取 JSON
- 逐行读取文件,并将数据插入变量和数组中
- 我遇到使用 c++ 逐行读取输入文件的问题
- 无法逐行读取.csv文件
- 在 c++ 中逐行读取文件(将代码从 Python 转换为 C++)
- 如何将文件逐行读取到矢量中,然后打印矢量
- C++逐行读取文件
- 如何逐行读取文件并分隔行组件?
- 使用"IF" C++逐行读取文本文件
- 使用字符串流逐行读取文件两次
- 向现有类添加一个方法以逐行读取文件的内容
- 逐行读取QString的最佳方法
- C++逐行读取文件的最快方法
- 逐行读取文本文件并计数比较运算符
- 如何在文本文件中逐行读取并填充指向对象数组的指针
- 逐行读取用户定义的文本资源文件
- 如何逐行读取文本文件中的字符串
- 内核模式:如何逐行读取 txt 文件