int main()
{
if (cin)
{
(...)
}
else
{
cerr << "No Data!!!" << endl;
}
}
我想检查输入框中是否有数据,但是即使我只在开头输入Ctrl+Z,错误消息也不会显示。
int main()
{
if (cin)
{
(...)
}
else
{
cerr << "No Data!!!" << endl;
}
}
我想检查输入框中是否有数据,但是即使我只在开头输入Ctrl+Z,错误消息也不会显示。
在你尝试读取之前,流并不知道是否存在任何有用的数据。至少你需要查看第一个字符,例如使用
if (std::cin.peek() != std::char_traits<char>::eof()) {
// do something with the potentially present input.
}
else {
// fail
}
更有可能是您需要依赖于一些非空数据。如果是这样,您可以查看文件中是否存在除空格以外的内容:
if (!(std::cin >> std::ws).eof())
...
操作器std::ws
将跳过前导空格。只有当遇到非空白字符或文件结尾时,它才会停止。如果到达文件结尾,std::cin.eof()
将返回true
。
一般来说,我不会费心读取第一个项目。如果根本没有读取任何内容,仍然可以视为失败:
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
}