【发布时间】:2017-04-07 04:56:45
【问题描述】:
我目前有这个功能:
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
当我输入例如“6+”时,它告诉我输入第一个数字,它会接受它,但会立即转到第二行并将其称为错误,我什至没有输入我的输入。
我认为这是因为第一个输入只接受“6”,而“+”转到第二个输入返回错误。所以while的参数肯定有问题。
【问题讨论】:
-
我认为你将不得不使用
getline并解析完整的行,而不是像那样使用cin -
但 Getline 读取为字符串
标签: c++ while-loop cin