After reading 3.99 into the variable "price" from the file with operator>>, the next character to read is the endline after "3.99" (that's just what operator>> does: it skips leading whitespace, and then reads exactly what's asked and not a character more)
You then call getline(), which reads everything up to and including the newline character, it does exactly that: it sees the newline character that's sitting there after the price, and reads that in, and it's done.
Now the next line to read is the line "Angie Laberdoodle". You're now calling "inFile >> number" to read an integer, but "Angie" is not an integer. operator>> reads nothign and sets the failbit on the stream
Your loop never checks the failbit, all input operations do nothing on a stream that has failbit set, and there you have an endless loop.
Two solutions:
1) skip the endline character after reading the price and before calling getline()
2) use getline for all input, and convert to int and to double later (that's the direction you took when you removed lines 17 and 23)
The first one is the easiest, so here it is:
replace "
inFile >> number >> price;
", both times, with
"
inFile >> number >> price >> ws;
"
Also, you're duplicating some code. Usually C++ file input loops place the read code inside the loop controlling statement, instead of once before the loop and once again inside:
1 2 3 4 5 6 7 8 9 10 11 12
|
int main()
{
string name;
int number;
double price;
ifstream inFile("inventory.dat");
while( getline(inFile, name)
&& inFile >> number >> price >> ws )
{
cout << name << " " << number << " " << price << '\n';
}
}
|