【发布时间】:2016-09-28 06:48:35
【问题描述】:
这是一个执行终端 IO 导航技术的示例程序。我正在尝试检查用户是否输入了错误的值。
// This program simply demonstrates nagivating through a Terminal I/O
// whilst checking that the user has not entered the wrong value for nagivation
#include <iostream>
#include <string>
using namespace std;
int main()
{
string user_input;
cout << "Would you like to withdraw (W) from or deposit (D) into your Bank Account?";
cin >> user_input;
// Here I would like to check whether the user has entered some wrong value - say "e", "f", or even "glirebglhbgeriuub",
// and if they have entered the wrong value, they get an error message and asked to enter again
// I would also like to know how to use a more generic incorrect user input detection method
// Any ideas?
# Do other things here depending upon whether the result was "W" or "D"...
return EXIT_SUCCESS;
}
编辑:这是我过去尝试过的,但我不确定这是否是最好的方法:
cout << "Would you like to withdraw (W) from or deposit (D) into your Bank Account?" << endl;
cout << "-> ";
cin >> user_input;
while ((user_input != "W") && (user_input != "D"))
{
cout << "Would you like to withdraw (W) from or deposit (D) into your Bank Account?" << endl;
cout << "-> ";
cin >> user_input;
}
if (user_input == "W")
{
// DO STUFF
}
else if (user_input == "D")
{
// DO STUFF
}
【问题讨论】:
-
到目前为止您尝试了哪些方法,为什么没有成功?
-
我已经看到了多种解决此问题的方法,其中大多数涉及使用一种形式的 while 循环。我很好奇在检查用户是否输入正确的输入时是否有某种“标准”。
-
" 我很好奇是否有某种“标准”" 不,没有。你做最适合你的事情。
-
与其检查错误的值,不如检查正确的值,如果没有找到正确的值,就假设它是错误的。
-
您追求的是特定的 c++ 语法吗?有很多方法可以做到这一点。查看“if”条件和“switch”语句。