Yes or no loop help

Trying to figure out how to loop this code with using the const int maxchar = 3; instead just using yes or no to determine because it works but if you use any word it'll work and i don't want that to happen just yes or no

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    const int maxchar = 3;
    string answer;
    while (true)
    {
       cout << "Do you want to close the program? " << endl;
       cin >> answer;
       if (answer.size() < maxchar)
       {
         cout << "Why not?" << endl;
         continue;
       }
       else
       {
          cout << "Ok Bye Bye " <<endl;
          break;
       }
   }

   return 0;
}
At line 12, instead of testing for size, test the contents of answer for "yes" or "no".
you should test
if(answer == "yes")

but, most folks would convert the input to upper or lower case and then test against the appropriate value so it triggers off yes, Yes, YES, yEs, etc




Last edited on
so
if (answer == y) would work?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string> //NECESSARY!
//#include <iomanip>//not necessary
//using namespace std; == bad-practice
//http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
int main()
{
    std::string answer;
    bool Quit = false;
    while (!Quit)
    {
        std::cout << "Do you want to close the program? \n";
        getline(std::cin, answer);
        if(answer == "No")//might also check NO, nO, no, etc
        {
            std::cout << "Why not?\n";
            // continue;
        }
        else if(answer == "Yes")//might also check yes, YES, yEs, etc
        {
            std::cout << "Ok Bye Bye \n";
            Quit = true;
            //  break;
        }
        else
        {
            std::cout << "Wrong entry, try again \n";
        }
    }
}
is there a way to cover every version of yes and no or do you have to write everyone out
is there a way to cover every version of yes and no or do you have to write everyone out

easiest would be to uppercase or lowercase the answer string throughout and then check if its yes or no
http://stackoverflow.com/questions/313970/how-to-convert-stdstring-to-lower-case
Last edited on
it would be == "y" but that would work. y is a variable. 'y' is a character. "y" is a string. You have a variable in your question.

you can lump together with converting to lowercase and then using some simple ors..

if(answer == "y" || answer == "yes" || others...)


Topic archived. No new replies allowed.