Ctrl-D
makes the standard input report EOF but leaves the file open. You can reuse std::cin
after EOF, as the following simple program demonstrates:
#include <iostream>
#include <string>
int main()
{
for (;;)
{
for (std::string s; std::cin >> s; )
{
std::cout << "Got token: " << s << "\n";
}
std::cin.clear();
std::cout << "Received EOF\n";
}
}
Now, when parsing integers, there's the possibility of a parsing error. In that case, the stream is not EOF, but in "fail" state. You also need to clear the error, but you also need to discard the unparseable values. For that you need ignore
:
#include <iostream>
#include <limits>
int main()
{
for (;;)
{
for (int n; std::cin >> n; )
{
std::cout << "Got integer: " << n << "\n";
}
if (std::cin.eof())
{
std::cout << "Received EOF\n";
std::cin.clear();
}
else
{
std::cout << "Parsing failure\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
}
Your error in using ignore
was twofold: You were only ignoring one character, even though the input could conceivably consist of more than one unparseable character, and you were ignoring up to EOF, rather than up to the next newline: That's because ignore()
has default arguments, and ignore()
is the same as ignore(1, EOF)
.