0

So here's my code:

 b:
        cout << "\nDo you want to continue (Y/N)? ";
        cin >> ans;
        if (ans == 'y' || ans == 'Y')
            goto a;
        else if (ans == 'n' || ans == 'N')
            goto c;
        else
            cout << "Invalid Answer!";
        goto b;

my problem is if I enter 2 or more letters, it reads all and throws "invalid answer!" and prints "do you want to continue (y/n)" as many as the letters i've input. like this one

Do you want to continue (Y/N)? asd
Invalid Answer!
Do you want to continue (Y/N)? Invalid Answer!
Do you want to continue (Y/N)? Invalid Answer!
Do you want to continue (Y/N)?

2 Answers2

0

your code is reading each character and displaying a result for each character, I think reading it as a string and getting the first character will solve it but i would recommend using getch()

Anuswadh
  • 542
  • 1
  • 11
  • 19
  • 2
    `getch()` - like `` is not standard C++. It is an extension specific to some vendors. – Peter Mar 12 '16 at 10:26
0

You should add:

std::cin.clear();
std::cin.ignore(INT_MAX);

to clear the input. In your case, your code should become:

 b:
        cout << "\nDo you want to continue (Y/N)? ";
        cin >> ans;
        if (ans == 'y' || ans == 'Y')
            goto a;
        else if (ans == 'n' || ans == 'N')
            goto c;
        else
            cout << "Invalid Answer!";
            cin.clear();
            cin.ignore(INT_MAX);
        goto b;
Duy Kha Đinh
  • 58
  • 1
  • 6
  • Personally, I prefer `std::cin.ignore(std::numeric_limits::max(), '\n');` As the standard stipulates that if the first parameter is exactly equal to `numeric_limits::max()`, the "extract up to X characters" test is ignored (http://en.cppreference.com/w/cpp/io/basic_istream/ignore , http://www.cplusplus.com/reference/istream/istream/ignore/ ), this means it'll extract as many characters as it can until it extracts a newline, at which point it stops. On any system that stores Enter as `\n`, this effectively discards everything that you typed before pressing Enter. – Justin Time - Reinstate Monica Mar 12 '16 at 20:06