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.