C++ formatted input with streams can be a pain in the neck sometimes.
The
getline
function will get a line upto the first
'\n'
that it encounters. It will remove this
'\n'
from the stream.
This means that if the first character that
getline
encounters is the newline character, you will get an empty string returned.
With
chars, int, float
and such the behaviour is somewhat different. If will ignore any amount of consecutive
'\n'
at the start of a number. Once it start collecting the number It will stop when it comes across a non useful character such as newlines, spaces, etc AND IT WILL LEAVE THESE CHARACTERS IN THE STREAM.
So your code actually works like this:
1. Read the first line OK (removes newline from stream)
2. get the first
length ok (but leaves newline in stream)
3. get the first
retail OK - (but leaves newline in stream.)
4. Tries to get next line - get empty string beause of newline character.
5. Tries to get second
length - FAILS - because first character it finds is a letter (leaves this letter in stream). Length variable is not changed
The stream is now marked as failed - all subsequent stream reads will now fail.
Now that we know what the problem is we can re-arrange your code like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
getline(indata, model);
outdata << setw(16) << model << " ";
indata >> length;
outdata << setw(6) << length << " ";
indata >> retail;
outdata << setw(8) << retail << endl;
indata.ignore(1,'\n');//remove problem newline char
getline(indata, model);
outdata << setw(16) << model << " ";
indata >> length;
outdata << setw(6) << length << " ";
indata >> retail;
outdata << setw(8) << retail << endl;
indata.ignore(1,'\n'); //remove problem new line char
getline(indata, model);
outdata << setw(16) << model << " ";
indata >> length;
outdata << setw(6) << length << " ";
indata >> retail;
outdata << setw(8) << retail << endl;
|