C++istream输入失败,但会消耗数据.失败后应能够读取坏数据



我对iostream的理解一直是,当输入转换失败时,数据会保留在流中,以便在清除错误后读取。但我有一个例子并不总是这样,我想知道这种行为是否正确。如果是的话,有人能给我指一些关于实际规则的好文件吗?

这个小程序代表了使用i/o失败读取可选重复计数和字符串的想法。

#include <iostream>
#include <string>
int main()
{
int cnt;
std::cout << "in: ";
std::cin >> cnt;
if(!std::cin) {
cnt = 1;
std::cin.clear();
}
std::string s;
std::cin >> s;
std::cout << "out: " << cnt << " [" << s << "]" << std::endl;
}

因此,以下是它的运行方式:

[me@localhost tmp]$ ./bother 
in: 16 boxes
out: 16 [boxes]
[me@localhost tmp]$ ./bother 
in: hatrack
out: 1 [hatrack]
[me@localhost tmp]$ ./bother 
in: some things
out: 1 [some]
[me@localhost tmp]$ ./bother 
in: 23miles
out: 23 [miles]
[me@localhost tmp]$ ./bother 
in: @(#&$(@#&$ computer
out: 1 [@(#&$(@#&$]

所以它基本上是有效的。当首先有一个数字时,它被读取,然后字符串被读取。当我首先给出一个非数字时,读取失败,计数被设置为1,非数字输入被读取。但这打破了:

[me@localhost tmp]$ ./bother 
in: + smith
out: 1 [smith]

+无法读取整数,因为它不足以生成一个数字,但+不会保留在要由字符串读取的流中。与-类似。如果它将+或-读取为零,这是合理的,但读取应该成功,cnt应该显示零。

也许这是正确的行为,而我一直对它应该做什么是错误的。如果是这样,规则是什么?

谢谢你的建议。

加号和减号是整数的有效部分,因此被读取,当读取下一个字符时,流会失败,该字符会留在流中,但前导符号不会放回流中。

请参阅https://en.cppreference.com/w/cpp/locale/num_get/get对于完整的规则

最新更新