0 c++ string validation loops input
我只是在学习C++(1周的经验),并且正在尝试编写一个输入验证循环,要求用户输入"是"或"否".我想通了,但感觉有更好的方法来接近这个.这是我想出的:
{
char temp[5]; // to store the input in a string
int test; // to be tested in the while loop
cout << "Yes or No\n";
cin.getline(temp, 5);
if (!(strcmp(temp, "Yes")) || !(strcmp(temp, "No"))) // checks the string if says Yes or No
cout << "Acceptable input"; // displays if string is indeed Yes or No
else //if not, intiate input validation loop
{
test = 0;
while (test == 0) // loop
{
cout << "Invalid, try again.\n";
cin.getline(temp, 5); // attempts to get Yes or No again
if (!(strcmp(temp, "Yes")) || !(strcmp(temp, "No"))) // checks the string if says Yes or No
test = 1; // changes test to 1 so that the loop is canceled
else test = 0; // keeps test at 0 so that the loop iterates and ask for a valid input again
}
cout << "Acceptable input";
}
cin.ignore();
cin.get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我为我糟糕的笔记道歉,不确定什么是相关的.我也在使用cstring标头.
更好的IMO:
std::string answer;
for(;;) {
std::cout << "Please, type Yes or No\n";
getline(std::cin, answer);
if (answer == "Yes" || answer == "No") break;
}
Run Code Online (Sandbox Code Playgroud)
您还可以将答案转换为小写,允许用户不仅键入"是",还可以键入"是","yEs"等.请参阅此问题
归档时间: |
|
查看次数: |
5388 次 |
最近记录: |