5
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.

Catiger3331
  • 611
  • 1
  • 6
  • 18
  • I don't want to read in from cin at the beginning, as the first entry might be useful. – Catiger3331 Dec 14 '15 at 19:01
  • Possible duplicate of [cin.eof() functionality](http://stackoverflow.com/questions/4939251/cin-eof-functionality) – GingerPlusPlus Dec 14 '15 at 19:02
  • 1
    Possible duplicate of [checking data availability before calling std::getline](http://stackoverflow.com/questions/3317740/checking-data-availability-before-calling-stdgetline) – Captain Obvlious Dec 14 '15 at 19:06

1 Answers1

5

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.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380