Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have written a simple program that reads character input from the keyboard wit

ID: 658940 • Letter: I

Question

I have written a simple program that reads character input from the keyboard within a For loop. My professor has taken away 10 points for not checking the input using cin.eof. I don't understand why this is necessary? Presumably any non-integer character should be acceptable. The prof specifically said not to check for integers.

I ran the program using Visual Studio 10, and entered CTRL-Z as input. The program quit anyway even though I did not specifically code for the EOF condition. Can someone explain why? And is the professor correct insisting to check for cin.eof or is this antiquated style?

Here is an example code snippet:

cout << "Enter a list of 10 words" << endl;

for (i= 0;i< MAX; i++) {
    getline(cin, input);
    Word word(input);
    noun_array[nElements]= word;
}

Explanation / Answer

I ran the program using Visual Studio 10, and entered CTRL-Z as input. The program quit anyway even though I did not specifically code for the EOF condition. Can someone explain why?

The program doesn't quit.

The end-of-file character (CTRL-Z on the keyboard) sets the internal state flag of std::cin to eofbit, which must be cleared with basic_ios::clear() before following calls to getline will work properly.

The loop is executed MAX times but getline won't append characters to input.

I'm not sure this is what you want. If it works, it's probably a matter of luck.

How to check? eof() has some downsides:

Both eof() and feof() check the state of an input stream to see if an end-of-file condition has occurred. Such a condition can only occur following an attempted read operation. If you call either function without previously performing a read, your code is wrong! Never loop on an eof function.

(From All about EOF)

The EOF state may not get set until after a read is attempted past the end of file. That is, reading the last byte from a file might not set the EOF state.

Moreover

if (!std::cin.eof())
will test for end-of-file, not for errors.

You should prefer:

if (getline(std::cin, input))
{
// ...
}
See also C++ FAQ Section 15.5 and How to determine whether it is EOF when using getline() in c++?

EDIT

It should be something like:

std::cout << "Enter a list of 10 words" << std::endl;

for (unsigned i(0); i < MAX && std::getline(std::cin, input); ++i)
{
// ...
// Word word(input);
// noun_array[nElements] = word;
// ...
}
This way the program performs its processing only with a valid input.