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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With