简体   繁体   English

C ++文件IO getline无法提取字符串

[英]C++ file IO getline not pulling a string

I have a file that is opened filled like this: 我有一个打开的文件,填充如下:

STRING

INT INT

INT INT

INT INT

filename.txt FILENAME.TXT

STRING

INT INT

INT INT

INT INT

filename1.txt filename1.txt

etcetera 诸如此类

I have code that is supposed to read from the file, pull the string, the integers, and the file names. 我有应该从文件读取的代码,提取字符串,整数和文件名。 It is able to pull the string and the integers, but it won't pull the file name. 它能够提取字符串和整数,但不会提取文件名。

Here is the code: 这是代码:

while( !input.eof() )
{
   string name;
   int type = UNKNOWN;
   int pages;
   float ounces;
   getline( input, name );
   input >> type >> pages >> ounces;
   getline(input, reviewFile); //reviewFile is a static string called in the header file
   input.ignore(INT_MAX, '\n');
}

The operator>> will read words, not taking end of line into account that much. 运算符>>会读单词,而不会过多考虑行尾。

Therefore, I would write something like this (As Massa wrote in a comment): 因此,我将编写如下内容(如Massa在评论中所写):

input >> type >> pages >> ounces >> ws;

Also, please note that "eof" checks are suboptimal. 另外,请注意,“ eof”检查次优。 Try to avoid them. 尽量避免它们。 Moreover, you do not check after the reads within the loop if there is anything more to read. 此外,您无需在循环内的读取之后检查是否还有其他要读取的内容。

It should work if you put the ignore before the getline, to eat the newline after the ounces: 如果您将ignore放在getline之前,然后在盎司之后吃掉换行符,则应该起作用:

while( !input.eof() )
{
   string name;
   int type = UNKNOWN;
   int pages;
   float ounces;
   getline( input, name );
   input >> type >> pages >> ounces;
   input.ignore(INT_MAX, '\n');
   getline(input, reviewFile); //reviewFile is a static string called in the header file
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM