简体   繁体   中英

reading multiple lines from a file using getline?

I am trying to read in the data in a names.txt file and output the full name and ideal body weight for each person. Using a loop to read the names and feet and inches of each person from the file. The file reads:

Tom Atto 6 3 Eaton Wright 5 5 Cary Oki 5 11 Omar Ahmed 5 9

I'm using the following code for this:

string name;
int feet, extraInches, idealWeight;
ifstream inFile;

inFile.open ("names.txt");

while (getline(inFile,name))
{
    inFile >> feet;
    inFile >> extraInches;

    idealWeight = 110 + ((feet - 5) * 12 + extraInches) * 5;

    cout << "The ideal weight for " << name << " is " << idealWeight << "\n";

}
inFile.close();

when i run this im getting output:

The ideal weight for Tom Atto is 185 The ideal weight for is -175

Add this statement in while loop after reading the two extraInches value.

inFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

It ignores the '\\n' after the second integer you read in while loop. You may refer: Use getline and >> when read file C++

You are running into problems because after the line

inFile >> extraInches;

is executed in the first iteration of the loop, there is still a newline character in the stream. The next call to getline simply returns an empty line. The subsequent call

inFile >> feet;

fails but you don't check whether the call was successful.

Couple of things I want to mention in relation to your problem.

  1. Mixing unformatted input, using getline , and formatted input, using operator>> is fraught with problems. Avoid it.

  2. To diagnose IO related problems, always check the state of the stream after an operation.

In your case, you can use getline to read lines of text, and then use istringstream to extract numbers from the lines.

while (getline(inFile,name))
{
   std::string line;

   // Read a line of text to extract the feet
   if ( !(inFile >> line ) )
   {
      // Problem
      break;
   }
   else
   {
      std::istringstream str(line);
      if ( !(str >> feet) )
      {
         // Problem
         break;
      }
   }

   // Read a line of text to extract the inches
   if ( !(inFile >> line ) )
   {
      // Problem
      break;
   }
   else
   {
      std::istringstream str(line);
      if ( !(str >> inches) )
      {
         // Problem
         break;
      }
   }

    idealWeight = 110 + ((feet - 5) * 12 + extraInches) * 5;

    cout << "The ideal weight for " << name << " is " << idealWeight << "\n";

}

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