I create file grades.txt and write on this "dani"
All your read operations should fail, because "dani" cannot be extracted as an integer. This sets the failbit of the stream but does not consume any characters and therefore doesn't set eofbit. Both your programs should be stuck in an infinite loop.
fix i not put dani i put "100"
Ok, then you won't get the infinite loop :) I've written a program to demonstrate the problem:
istringstream input("100");
int foo;
cout << "Reading int succesfully" << endl;
input >> foo;
cout << "!input:\t" << boolalpha << !input << endl;
cout << "input.eof():\t" << boolalpha << input.eof() << " << pay attention" << endl << endl;
cout << "Attempting to read eof" << endl;
input >> foo;
cout << "!input:\t" << boolalpha << !input << endl;
cout << "input.eof():\t" << boolalpha << input.eof() << endl << endl;
input.clear();
input.str("c");
char c;
cout << "Reading char succesfully" << endl;
input >> c;
cout << "!input:\t" << boolalpha << !input << endl;
cout << "input.eof():\t" << boolalpha << input.eof() << " << pay attention" << endl << endl;
cout << "Attempting to read eof" << endl;
input >> c;
cout << "!input:\t" << boolalpha << !input << endl;
cout << "input.eof():\t" << boolalpha << input.eof() << endl << endl;
And the output:
Reading int succesfully
!input: false
input.eof(): true << pay attention
Attempting to read eof
!input: true
input.eof(): true
Reading char succesfully
!input: false
input.eof(): false << pay attention
Attempting to read eof
!input: true
input.eof(): true
So, the behaviour of eofbit is different when reading a single character compared to when reading a formatted input such as numbers.
Therefore if you want to modify your version of the loop such that it behaves the same way for numbers and characters, you'll need to check the streams status using the bool conversion instead of eof()
. Additionally, that would prevent infinite loop on invalid input. You could use fail()
instead but that doesn't check for badbit so it won't have desired behaviour when you get i/o error.
infile.get(c);
while (infile) // or !infile.fail() if you have infallible hardware
{
// use c
infile.get(c);
}
Should work as well as
int tmpGrade;
inGrade >> tmpGrade;
while (inGrade)
{
// use tmpGrade
inGrade >> tmpGrade;
}
However, your approach duplicates the input call. You can avoid that by getting the input in the loop condition:
while (inGrade >> tmpGrade)
{
// use tmpGrade
}