简体   繁体   中英

C++ file IO getline not pulling a string

I have a file that is opened filled like this:

STRING

INT

INT

INT

filename.txt

STRING

INT

INT

INT

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):

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

Also, please note that "eof" checks are suboptimal. 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:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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