C++ C++;stringstream输入的各种结果
我正在尝试一个“stringstream”程序,它是这样的:C++ C++;stringstream输入的各种结果,c++,stringstream,C++,Stringstream,我正在尝试一个“stringstream”程序,它是这样的: #include <iostream> #include <sstream> using namespace std; int main() { int x; char ch; std::string myString; cout<< "input an integer:-" << endl; while (getline ( cin, myString )) { std::is
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
int x;
char ch;
std::string myString;
cout<< "input an integer:-" << endl;
while (getline ( cin, myString ))
{
std::istringstream strin(myString);
strin >> x;
if (!strin)
{
cout << "Bad 1 input \'" << strin.str() << "\'" << endl;
}
else if ( strin >> ch )
{
cout << "Bad 2 input \'" << ch << "\'" << endl;
}
else
{
cout << "You entered: " << x << endl;
break;
}
}
cout<< "good";
return 0;
}
我在这里指出了我的问题:
问题1:为什么这里没有抛出错误输入1?如果抛出错误输入2,为什么ch等于“.”而不是0
问题2:为什么不抛出错误输入1?为什么ch等于3
问题3:为什么没有(再次)抛出错误输入1?(这也会询问为什么输出给出的是's'而不是'2 string')
问题4:为什么输出与问题3不相似
我无法理解为什么会发生这种情况。Stringstream会根据字符分析输入。如果它开始解析一个int,这是在问题#1-3期间发生的事情,它就不会抛出badinput 1 它使用的过程是这样的
- 如果是,则存储并继续,否则返回错误1李>
- 如果是,则存储并继续,再次运行步骤2
- 如果否,它是结尾字符,即
还是空白“\0”
- 如果是,很好。但是如果是空白,如果除了“
”或更多空白之外还有其他字符,则出现错误2\0
- 否则,错误二
- 如果是,很好。但是如果是空白,如果除了“
5
),因此避免了错误。但是,由于第二个是。
,因此它在输入结束之前遇到了一个坏字符2
),因此避免了错误字符。但是下一个字符是一个空格,后跟'3'
,它不能生成整数,导致错误2'2'
,一个数字。这里没有错误。然后是一个空格,后跟's'
。这里没有int。错误2's'
,它显然不是数字。错误1除非启用异常,否则流永远不会抛出。。。你必须对每个人都这样做stream@Dieter为何要删除这个问题。即使如此,也不意味着这真的是一种解释!Thnk u
input an integer:-
he is there
Bad 1 input 'he is there'
5.0
Bad 2 input '.' // problem 1
2 3
Bad 2 input '3' // problem 2
2 string
Bad 2 input 's' // problem 3
c string
Bad 1 input 'c string'
string 2
Bad 1 input 'string 2' // problem 4
5
You entered: 5
good