【发布时间】:2020-05-13 02:53:26
【问题描述】:
在下面的代码中,输入是9/ 8,那为什么B不把8作为输入呢?
#include <iostream>
using namespace std;
int main(){
int A, B;
cin >> A >> B;
}
【问题讨论】:
-
问问你自己,
9/中的/发生了什么
在下面的代码中,输入是9/ 8,那为什么B不把8作为输入呢?
#include <iostream>
using namespace std;
int main(){
int A, B;
cin >> A >> B;
}
【问题讨论】:
9/ 中的/ 发生了什么
输入为 9/ 8 为什么 B 不将 8 作为输入?
因为“/8”不是数字。
【讨论】:
operator>> 在遇到不适合正在读取的数据类型的字符时停止读取。
在这种情况下,您对operator>> 的第一次调用正在读取int A,因此它会读取'9' 字符,然后在遇到非数字'/' 字符时停止读取。 '/' 字符保留在输入流中。
然后您对operator>> 的第二次调用尝试读取int B,但它读取的是'/' 字符而不是'8' 字符,因此读取失败,因为'/' 不是数字。
您需要忽略'/' 才能读取'8' 字符,例如:
#include <iostream>
using namespace std;
int main(){
int A, B;
char ignore;
cin >> A >> ignore >> B;
}
或者:
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int A, B;
cin >> A >> ws;
cin.ignore();
cin >> B;
}
【讨论】: