使用字符串在C ++中输入验证循环

时间:2011-03-28 08:01:54

标签: 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;
}

我为我的可怜的笔记道歉,不确定什么是相关的。我也在使用cstring标头。

2 个答案:

答案 0 :(得分:5)

更好的IMO:

std::string answer;

for(;;) {
    std::cout << "Please, type Yes or No\n";
    getline(std::cin, answer);

    if (answer == "Yes" || answer == "No") break;
}

您还可以将答案转换为小写,不仅允许用户键入“是”,还可以键入“是”,“yEs”等。请参阅this question

答案 1 :(得分:0)

我想你想做一个while循环:

bool test = false;
do 
{
   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
       test = true;
   }
   else
   {
       cout << "Invalid, try again.\n";
   }

} while (!test);