0

I'm just learning C++ (1 week of experience) and was trying to write an input validation loop that ask the user to enter "Yes" or "No". I figured it out but have a feeling there's a better way of approaching this. Here's what I came up with:

{
    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;
}

I apologize for my poor notes, not sure what is relevant. I'm also using the cstring header.

tho121
  • 3
  • 1
  • 3

2 Answers2

5

Even better IMO:

std::string answer;

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

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

You also can transform answer into lower case that allows user to type not only "Yes", but also "yes", "yEs", etc. See this question

Community
  • 1
  • 1
maverik
  • 5,508
  • 3
  • 35
  • 55
  • 1
    Using `std::string` is certainly better as not only is it C++, it reduces the risk of buffer overflow and it makes string comparisons easier to read. However, this answer does not allow "no" (and its case variants) as valid input. – johnsyweb Mar 28 '11 at 08:48
0

I think you want a do while loop:

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);
ChrisWue
  • 18,612
  • 4
  • 58
  • 83