C++ 使用 getline() 从文件中读取多行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20756968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:18:18  来源:igfitidea点击:

Reading multiple lines from a file using getline()

c++file-iogetline

提问by Ghost Repeater

I am trying to read in and then output the contents of a text file with three lines, as follows:

我试图读入然后输出三行文本文件的内容,如下所示:

Bob Dylan 10 9

鲍勃·迪伦 10 9

John Lennon 8 7

约翰列侬 8 7

David Bowie 6 5

大卫鲍伊 6 5

For each line, I just want to output the line, i.e. firstName LastName number1 number2.

对于每一行,我只想输出该行,即 firstName LastName number1 number2。

I'm using the following code for this:

我为此使用以下代码:

int num1;
int num2;
string firstName;
string lastName;
string fullName; 
ifstream inFile;

inFile.open("inputFile.txt");

while (getline(inFile, firstName))
    {
        inFile >> firstName >> lastName >> num1 >> num2;

        fullName = firstName + " " + lastName;

        cout << fullName << " " << num1 << " " << num2 << endl;
    }

inFile.close();

There are 2 problems with the output from this. First, the first line is not output, although from experimentation I know that it DOES read it in. Second, after the last 2 lines are read in and output (as desired), the program displays everything in the last line EXCEPT the first name (in this case the last thing it prints is Bowie 6 5).

这个输出有两个问题。首先,第一行不是输出,虽然从实验中我知道它确实读入了它。其次,在读入最后两行并输出(根据需要)后,程序显示最后一行中的所有内容,除了名字(在这种情况下,它打印的最后一件事是 Bowie 6 5)。

Can someone use this simple example to explain how the getline function works when reading in multiple lines from a file? (I don't even know if it's the best way, but it's the only way I know as of yet). Here are some specific questions.

有人可以使用这个简单的示例来解释从文件中读取多行时 getline 函数的工作原理吗?(我什至不知道这是否是最好的方法,但这是我目前所知道的唯一方法)。下面是一些具体的问题。

First, does the while loop conditional getline(inFile, firstName) return a boolean? If so, how can it be true (i.e. how can the while loop start) if I haven't given firstName a value yet? Is it the case that the program reads the first line and if there's something there, then it executes the while loop, but starting with the second line, because it already used the first to check for content?

首先,while 循环条件 getline(inFile, firstName) 是否返回布尔值?如果是这样,如果我还没有给 firstName 一个值,它怎么会是真的(即 while 循环如何开始)?是不是程序读取第一行,如果那里有东西,然后它执行while循环,但从第二行开始,因为它已经使用第一行来检查内容?

Second, if firstName does have a value, and if that value is the first name on the first line ("Bob" in this case), why isn't the first line output at all? I've been racking my brain trying to figure out where it went to.

其次,如果 firstName 确实有一个值,并且如果该值是第一行的名字(在本例中为“Bob”),为什么第一行根本没有输出?我一直在绞尽脑汁想弄清楚它去了哪里。

Third, after the program reads in and displays the last two lines, the program moves to the next line and encounters nothing but blanks, right? Then what would be the value of firstName? Would it be blank, or would it still be "David"? If it's blank, why does the while loop execute again? But if it's "David", then why does the program not output that value along with the others?

第三,程序读入并显示最后两行后,程序移动到下一行,遇到的只有空格,对吗?那么 firstName 的值是什么?它会是空白的,还是仍然是“大卫”?如果它是空白的,为什么while循环会再次执行?但是,如果是“David”,那么为什么程序不与其他值一起输出该值?

Btw, I am working out of a textbook (not for homework), and it covers getline, but not for multiple lines. But then the exercises involve multiple lines, so I'm a bit lost.

顺便说一句,我正在使用教科书(不是用于家庭作业),它涵盖了 getline,但不适用于多行。但是练习涉及多行,所以我有点迷茫。

回答by Abhishek Bansal

You are trying to read each line twice.

您正试图将每一行读两遍。

while (getline(inFile, firstName)) // reads the line
    {
        // reads the next line and overwrites firstName!
        inFile >> firstName >> lastName >> num1 >> num2;

Change it to:

将其更改为:

while ( inFile >> firstName >> lastName >> num1 >> num2 )
{
    fullName = firstName + " " + lastName;
    cout << fullName << " " << num1 << " " << num2 << endl;
}

EDIT: To answer your questions:

编辑:回答你的问题:

How does getline() work?
Reads the entire line up to '\n' character or the delimiting character specified. http://www.cplusplus.com/reference/string/string/getline/?kw=getline

getline() 如何工作?
读取整行直到 '\n' 字符或指定的定界字符。http://www.cplusplus.com/reference/string/string/getline/?kw=getline

After reading the line, the control goes to the next line in the file.
Also, it returns a boolean value of true if the read operation was successful, else false.

读取该行后,控件转到文件中的下一行。
此外,如果读取操作成功,则返回布尔值 true,否则返回 false。

The extraction operator truncates on all whitespaces by default. It also returns a boolean value indicating whether the operation was successful.

默认情况下,提取运算符会截断所有空格。它还返回一个布尔值,指示操作是否成功。