Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check cin is end of file?

Tags:

c++

int main()
{
    if (cin)
    {
        (...)
    }
    else
    {
        cerr << "No Data!!!" << endl;
    }
}

I want to check if the input has any data, but the error message won't be displayed even if I only input Ctrl+Z at the beginning.

like image 876
Catiger3331 Avatar asked Dec 14 '15 18:12

Catiger3331


1 Answers

Before you attempted to read, the stream won't know whether there is any useful data. At the very least you'll need to look at the first character, e.g., using

if (std::cin.peek() != std::char_traits<char>::eof()) {
    // do something with the potentially present input.
}
else {
    // fail
}

More likely you'll depend on some non-space data to be available. If so, you could see if there is something other than space in the file:

if (!(std::cin >> std::ws).eof())
  ...

The manipulator std::ws will skip leading whitespace. It will stop when either a non-whitespace character or the end of file is reached. If the end of file is reached, std::cin.eof() will be true.

In general, I wouldn't bother but rather try to read the first item. If nothing at all is read it would still be viable to fail:

bool hasData = false;
while (std::cin >> some >> data) {
    hasData = true;
    // do something with the input
}
if (!hasData) {
    // report that there was no data at all
}

The no data case may be implicitly testable, e.g., by looking at the size of a read data structure.

like image 82
Dietmar Kühl Avatar answered Oct 16 '22 01:10

Dietmar Kühl