我目前有这个功能:
double GrabNumber() {
double x;
cin >> x;
while (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "You can only type numbers!\nEnter the number: ";
cin >> x;
}
return x;
}
其目的是检查x
是否为有效号码,如果有效则返回;如果不是,则返回cin >> x
。
在此功能期间调用它:
void addition() {
cout << "\nEnter the first number: ";
double a = GrabNumber();
cout << "Enter the second number: ";
double b = GrabNumber();
// rest of code
当我输入例如&#34; 6 +&#34;当它告诉我输入第一个数字时,它会接受它,但会立即转到第二行并将其称为错误,我甚至没有输入我的输入。
我认为这是因为第一个输入只接受&#34; 6&#34;而&#34; +&#34;转到第二个输入返回错误。因此,while
。
答案 0 :(得分:4)
如果您的输入立即成功,则不要忽略该行的其余部分,这将结束到下一个输入。这可以通过简单地复制cin.ignore
电话来解决。
double GrabNumber() {
double x;
cin >> x;
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // <--
while (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "You can only type numbers!\nEnter the number: ";
cin >> x;
}
return x;
}
我将此代码作为练习留下来干掉;)
答案 1 :(得分:2)