Yes or no loop help

Feb 8, 2017 at 6:42pm
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;
}
Feb 8, 2017 at 6:45pm
At line 12, instead of testing for size, test the contents of answer for "yes" or "no".
Feb 8, 2017 at 6:47pm
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 Feb 8, 2017 at 6:48pm
Feb 8, 2017 at 6:52pm
so
if (answer == y) would work?
Feb 8, 2017 at 7:00pm
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";
        }
    }
}
Feb 8, 2017 at 7:12pm
is there a way to cover every version of yes and no or do you have to write everyone out
Feb 8, 2017 at 7:19pm
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 Feb 8, 2017 at 7:22pm
Feb 8, 2017 at 7:22pm
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.