我试图重复读取整数,以及非整数的标记,以读取和处理它们作为字符串.我认为以下内容可行:
string s;
int x;
while(1) {
if (cin >> x) // try reading as int
cout << "read int: " << x << endl;
else { // try reading as string
cin.clear();
if (cin >> s)
cout << "read string: " << s << endl;
else
break; // eof
}
}
Run Code Online (Sandbox Code Playgroud)
但是,对于输入(在换行时使用换行符)
1 2 a
Run Code Online (Sandbox Code Playgroud)
它给出了输出
read int: 1
read int: 2
Run Code Online (Sandbox Code Playgroud)
似乎清除流的状态与之前不完全相同,实际上cin >> s失败了.为什么会这样,我怎样才能实现我想要的行为?
为了澄清,我无法将字符串解析为int,因为我尚未"学习"它.
| 归档时间: |
|
| 查看次数: |
190 次 |
| 最近记录: |