早上好!
我的问题:我在程序中声明输入 Y 表示是,N 表示否。如果用户输入是、否或随机字符串,它会说这是无效输入并再次询问。但假设用户输入“yes yes yes”,则会输出3次无效语句。我该如何解决这个问题?
我还需要对 bool 值做一些事情,因为它没有任何作用,因为如果他们说 n,我就会中断循环,但没关系。
这是我的代码片段:
bool done = true;
string ans;
try {
coeff input = readCoeffs();
results result = equSolver(input);
outResults(input, result);
while (done == true) {
cout << "Would you like to run the program again (Y to run again, N to close)? ";
cin >> ans;
if (ans == "Y" || ans == "y") {
coeff input = readCoeffs();
results result = equSolver(input);
outResults(input, result);
}
else if (ans == "N" || ans == "n") break;
else cout << "Invalid input. \n";
}
}
catch (const char* msg) {
cerr << msg << endl;
}
最佳答案
应该是
while(done == false)
Done 应该初始化为 false,并且在循环中,当输入 N 或 n 时将 did 设置为 true。这在某种程度上是一个风格问题,但通常最好避免中断,除非有非常充分的理由。
对于您的无效输入问题,您正在使用
cin >> ans;
这被空格打破了,所以输入“l m no p”将使程序说两次“无效输入”,然后退出。如果您想按行处理,请考虑使用 getline。
关于c++ - 再次提示运行程序: fixing if they put an invalid statement in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21761150/