如果输入流无效会怎样?例如如下:
int main()
{
int value;
while(!(cin>>value).eof());
}
如果输入的序列是:1 2 3 q 4 5,当cin扫描到'q'时,while会陷入死循环,值继续为3。 我的问题是: 1. 为什么 cin 不能忽略 'q' 并继续扫描 4? 2.输入流的底层实现是什么?有什么资料可以引用吗?
谢谢!
最佳答案
- Why can't cin ignore 'q' and proceed to scan 4?
如果你愿意,你可以。您可以通过以下方式获得该效果:
int value;
while(std::cin>>value);
if (!std::cin)
{
std::cin.clear(); // clear error state
std::cin.ignore(); // ignore the q
while(std::cin>>value); // read rest of values until 5
}
std::cin >> value
默认情况下只是不这样做,因为所需的行为因程序而异。对于许多人来说,这对 std::cin
是不受欢迎的忽略读取失败并继续扫描。默认行为允许程序员决定在失败时做什么。
另外,请注意 eof()
用于检查文件结尾。您不应该使用它来检查读取是否成功。常见的习语是:
while(std::cin>>value)
{
// Do stuff
}
- What's the underlying implementation fo input stream? Are there any materials I can refer to ?
std::cin
是一个全局静态对象,定义如下:
extern std::istream cin;
换句话说,它是 std::basic_istream<char>
的一个实例(std::istream 是它的类型定义)。
如果您想了解更多信息,这里有一些引用资料:
http://en.cppreference.com/w/cpp/io/cin
https://github.com/cplusplus/draft
但是,您很可能会受益于 good C++ book .
如果你想深入了解 iostreams,我也推荐 these articles .
关于c++ - 如果输入流无效会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19648991/