error with cin with char variable

Hi, I am a beginner of c++ and I am currently using code blocks just 2 let u all knw. I having a trouble when cin >> a variable with char. it will display error when user input yesssssssssssss but it display too muuch times, i just want it 2 display 1 time only. Please HELP!!!!!!!!!!!!!!!!!!!!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int main()
{
    char cont;
    do
    {
    do
    {
    cout << "Would you like to make another order(y/n) : ";
    cin >> cont;
    if (cont!= 'n' && cont != 'N' && cont !='y' && cont!= 'Y')
    {
        cout << "Please enter y or n only!!" << endl << endl;
    }
    }
    while(cont!= 'n' && cont != 'N' && cont !='y' && cont!= 'Y');
    }
    while (cont == 'y' || cont  == 'Y');
    return 0;
}
Last edited on
This is because it will continue to retrieve characters from the input stream. Try this instead:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <limits>

int main() {
    char cont;
    do {
        std::cout << "Would you like to make another order (y/n): ";
        std::cin >> cont;
        while (cont != 'n' && cont != 'N' && cont != 'y' && cont != 'Y') {
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            std::cout << "Please enter 'y' or 'n' only: ";
            std::cin >> cont;
        }
    } while (cont == 'y' || cont == 'Y');
    return 0;
}


What I did with the std::cin.ignore line is to tell the program to throw out the entire contents of the buffer until either the end of the stream is reached or a newline.
Last edited on
Also, you should use the OR (||) operator:

1
2
3
4
if (cont!= 'n' || cont != 'N' && cont !='y' || cont!= 'Y')
    {
        cout << "Please enter y or n only!!" << endl << endl;
    }
Also, you should use the OR (||) operator:



'n','N','y','Y' are all valid options. It has to be true that cont is not equal to all of those valid options for the error message to display.

If you have the || OR operator here and they enter for example 'n', a valid choice, this expression would evaluate to true, so the error message would display when it shouldn't.

while (cont != 'n' || cont != 'N' && cont != 'y' || cont != 'Y')
Registered users can post here. Sign in or register to post.