0
  do{
    cout<<"Enter the task to perform \n";
    cout<<"1. push an element \n";
    cout<<"2. pop an element \n";
    cout<<"3. peep the elements \n";
    cout<<"4. retain odd elements \n";
    cout<<"5. remove till element n \n";
    cout<<"6. Display the elements \n";
    cout<<"7. exit \n";
    cin>>a;
    switch(a){

        case 1:
        .
        .
        .
        .
        case 2:



        case 7:
        return 1;

        default:
        cout<<"Crap entry Reenter \n\n\n\n\n";

    }


}while(a != 7);
return 0;

This is my code where i am trying to make a stack And If i Enter a character in the switch case I get an infinite while loop Why is it so

  • What is the type of `a`? Because if it's e.g. `int` the input will only read an integer, and anything else will put the input stream `cin` in an error state. – Some programmer dude Feb 07 '15 at 09:21
  • A is an integer but I am getting infinite loop what do you mean by error state –  Feb 07 '15 at 09:51

2 Answers2

1

The switch then evaluates the character by its ASCII value, if the type of a is char.

If a is an int, inputting a character will set the cin stream to fail state (which can be queried with cin.fail()).

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • I am getting infinite loop please help me as to why it's so –  Feb 07 '15 at 09:53
  • @SagerGulabani Edited my answer. Check the answer [here](http://stackoverflow.com/a/19696468/3425536) on how to handle incorrect input with `cin`. – Emil Laine Feb 07 '15 at 10:06
1

Please note the the declaration of a and the way it is initialized are FUNDAMENTAL to provide a proper answer, so please let that declaration visible in your snippet.

By the way, if a is an integer and in cin there is something that cannot be read as an int, cin>>a fails, cin is blocked (so any further read will fail) and the value is not read.

As a consequence a will retain its old value (and chances are it will not be 7, so no return is done) and it will never be changed.

The proper way to ensure a read can be to use, istead of cin>>a,

while(!(cin>>a))
{
    cout << "bad input: re-enter" << std::endl;
    cin.cler(); 
    cin.ignore(numeric_limits<streamsize>::max(),'\n');
}

In other word, until cin>>a will not succeed, the error state is cleared, and whatever rubbish you may have int it, discarded, so that a new read will not re-read that same rubbish.

Emilio Garavaglia
  • 20,229
  • 2
  • 46
  • 63