Joseph Joseph - 1 month ago 7
C++ Question

Allowing multiple types of input for various forms of "yes" and "no" in C++

I posted a question about how to get user input such as YES or NO to control the flow of a program using if else statements, I got a answer and now i'm a step closer to making this work, however another problem has arisen, i really need to allow for multiple inputs, for example this is what im trying:

if (input == ("YES" || "yes" || "y" || "Yes" || "Y"))
{
cout << "you said yes" << endl;
}
else if (input == "NO", "no", "n", "No","N")
{
cout << "you said no" << endl;
}
else
{
cout << "ERROR!!!" << endl;
}


Kiril Kirov posted this code that could help:

if( std::string::npos != input.find( "no" ) )


but i couldn't get it to work, and roger pate suggested this:

if (prompt && cin.tie()) {
*cin.tie() << prompt << (default_yes ? " [Yn] " : " [yN] ");


however i never tried this as its complexity is far beyond my understanding. i was hoping for a solution a beginner programmer could understand or maybe im just a really slow learner




EDIT:
I made this modification but it still doesn't work any better then before, if i give the wrong case it goes to else (error) and there is no where to add more words, (such as NO N no No) :

cout << "\nYES or NO" << endl;
string input ="";
cin >> input;

if ( std::string::npos != input.find( "yes" ) )
{
cout << "you said yes" << endl;
}
else if ( std::string::npos != input.find( "no" ) )
{
cout << "you said no" << endl;
}
else
{
cout << "ERROR!!!" << endl;
}

Answer

Add the headers

#include <algorithm>
#include <cctype>

cout << "\nYES or NO" << endl; 
string input =""; 
cin >> input; 
transform (input.begin(), input.end(), input.begin(),tolower);

if ( (std::string::npos != input.find( "yes" )) || (std::string::npos != input.find( "y" )) ) 
{
     cout << "you said yes \n" ; 
}
else if ( (std::string::npos != input.find( "no" ) )  || (std::string::npos != input.find( "n" ) ) )
{
    cout << "you said no \n" ; 
}
else  
{
    cout <<  "ERROR!!! \n" ; 
}