如何在C 中逐行读取文本

how to read a text line by line in c++

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

我试图按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)