【发布时间】:2016-05-28 10:32:16
【问题描述】:
我正在开发一个程序,允许用户输入任意数量的双打,并将这些双打添加到向量中,直到用户输入“退出”,然后退出循环。
我需要这个输入函数在用户输入字符串或字符时不会失败,所以while (cin >> x) 是不可能的。
这是我的代码:
vector<double> input()
{
double x;
vector<double> scores;
cout << "Please enter a score: ";
while(true)
{
x = checkInput();
scores.push_back(x);
cout << "Enter another: ";
}
return scores;
}
double checkInput()
{
double x;
cin >> x;
while(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "That is not a number. Please enter another: ";
cin >> x;
}
return x;
}
这有效,并且如果用户输入无效输入也不会中断。但是,正如您所见,它永远不会从输入循环中中断。当用户输入==“退出”时,我需要它来打破并返回分数。我怎样才能做到这一点?
【问题讨论】:
-
使用
getline()阅读第一名。然后用std::istringstream提取你需要知道的内容。 -
使用 getline() 读取 std::string 然后使用 stod() 提取双精度值。如果它在读取字符串时需要继续工作,那么您需要使用字符串。
-
@JacobH 我试过这个方法,但是如果用户输入的不是“quit”(会中断)或数字,那么 stod() 会使程序崩溃。
-
@Kenta : 在使用 stod() 之前测试输入是否有效。
标签: c++ validation input while-loop cin