0

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;
}
Ron
  • 14,674
  • 4
  • 34
  • 47
  • 3
    Look at the type of `l`. is it a character type? – NathanOliver Feb 16 '18 at 16:49
  • 1
    Use a debugger and examine what is happening to the value of `l` in the loop and the conditional. Your instincts are good and by using the tools to see what's happening you will fix this easily. – TypeIA Feb 16 '18 at 16:53
  • Possible duplicate of [Why do I get an infinite loop if I enter a letter rather than a number?](https://stackoverflow.com/questions/19521320/why-do-i-get-an-infinite-loop-if-i-enter-a-letter-rather-than-a-number) – mkrieger1 Feb 16 '18 at 17:02

1 Answers1

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

jasinth premkumar
  • 1,430
  • 1
  • 12
  • 22
  • But why does the program not stop at `cin >> l` until the user enters something? How does that relate to the type of `l`? – mkrieger1 Feb 16 '18 at 16:56
  • @mkrieger1 it was explained [here](https://stackoverflow.com/questions/19521320/why-do-i-get-an-infinite-loop-if-i-enter-a-letter-rather-than-a-number/19521636#19521636) – jasinth premkumar Feb 16 '18 at 17:23