I am trying to compare the variable named response which contains a user's input, with an array of acceptable input strings named request001. When it finds an acceptable string, I want to it drop out of the loop and execute the next line of code. However, it just continues looping even when the input matches one of the strings in the array.
Here is my code:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
//declare variables
int i(1);
string response;
string request001 [12] { "stand", "stand up", "get up", "rise", "arise", "jump up", "leap up", "pop up", "spring up", "get to my feet", "jump to my feet", "spring to my feet" };
//Initiate dialogue with user.
cout << "\nWhat would you like to do?\n\n";
//Get user's input
getline (cin, response);
//Loops through an array named request001, comparing with a string named response.
while (request001[i] != response && i<13) {
i++;
cout << "\nI don't understand, \"" << response << ",\" please try again.\n\n";
getline (cin, response);
}
//Initiate next dialogue with user.
cout << "\nElevator opens.\n\n";
You should have noticed that you never tested for "stand". That is because in c++ array numbering starts from 0.
Also, please use code tags (the <> button on the left of your editing box), since it will allow for nice, formatted text.
As for your problem, you need two loops. One is a while loop, that just checks if you already entered a valid answer. You can use a bool type of condition, say
1 2 3 4 5 6 7 8 9 10
bool validAnswer(false);
while(!validAnswer)
{
//Initiate dialogue with user.
cout << "\nWhat would you like to do?\n\n";
//Get user's input
getline (cin, response);
...
}
Instead of the dots, now you can use a for loop, to check if response is in the array. Notice again that your for loop goes from 0 to 11 for(size_t i=0;i<12;i++)
If you find a valid answer, set validAnswer to true, and exit the for loop.
The last thing in the while loop is to print the "try again" message if validAnswer is false. If false, it will then try again. If true, you exit the while loop.
Alright, I am happy to report that with the help I received from ats15, (nobody else responded), I finally finished writing a short program that compares a string of user input against a preset string type array of valid inputs. Thank you for reminding me about the zero starting point in my string array. While not exactly the way you suggested, it certainly gave me enough to find my own way. The finished program is here: