简体   繁体   中英

Entering specific character into while loop

I am writing a code for class that asks the user to input a size that is an odd number equal to or greater than 7 . I have been able to make that part of my code work successfully. However, the next part consists of asking the user to enter a specific letter, in this case 'c' . If they do not enter 'c' then the loop should ask them to input another character. Whenever I run this code, it is creating an infinite loop whether I enter 'c' or another letter. I think my expression in my second while loop is incorrect, but I haven't been able to find a lot of information regarding this that could help me.

#include <iostream>
using namespace std;

int main() {

    int s, l;

    cout << "Welcome to the letter printer." << endl;
    cout << "Enter the size: " << endl;
    cin >> s;
    while (s < 7 || s%2==0 || s<0)
    {
        cout << "Invalid size. Enter the size again: " << endl;
        cin >> s;
    }

    cout << "Enter the letter: " << endl;
    cin >> l;
    while (l != 'c')
    {
        cout << "Invalid letter. Enter the letter again: " << endl;
        cin >> l;
    }

    return 0;
}

because you are getting char for int variable

wrong:

int s, l;

right one:

int s;
char l;

what is why it goes on infinite loop in second while

explanation for infinite loop

This is how basic_istream works. In your case when cin >> l gets wrong input - failbit is set and cin is not cleared. So next time it will be the same wrong input. To handle this correctly you can add check for correct input and clear&ignore cin in case of wrong input.

incorporated from here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM