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
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
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.
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++?
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.