-1

When I give a character input to 'choice', default statement is executed repeatedly. 'cin' instruction is not blocking the execution.

#include<iostream>
using namespace std;
main()
{
    int choice;



    do{
            cout<<"Enter your choice: ";
            cin>>choice; //I'm giving character i/p even though 'choice' is int
        switch(choice)
        {
            case 1:cout<<"\n 1 \n";
                   break;

            case 2:cout<<"\n 2 \n";
                   break;

            case 3:cout<<"\n 3 \n";
                   break;

            case 4:cout<<"\n 4 \n";
                   return 0;

           default:cout<<"An Invalid choice."<<endl;

        }

    }while(1);

        cout<<"\n Hello";
}
Lelouch Yagami
  • 159
  • 2
  • 10
  • Why don't you just enter numbers, which is what your `switch` statement implies? – Tim Biegeleisen Aug 15 '18 at 11:46
  • What is the reason default statement is executed infinitely when i give a character input accidentally. Why 'cin' is not blocking when it comes to next iteration? – Lelouch Yagami Aug 15 '18 at 11:54
  • You may want to do `if (cin>>choice) { switch... } else break;`. Where the switch is the entire current switch block. – Eljay Aug 15 '18 at 11:56
  • **Alwyas** check that input was successful. It just repeatedly fails. Has nothing to do with the `switch` statement at all. There are lots of questions/answers of that problem. – Dietmar Kühl Aug 15 '18 at 12:00

2 Answers2

-1

The cout statement shouldnt be blocking, that would be the cin you are referring to.

In this case, cin reading in the value, but NOT the newline after it, so the next time you read a value, you are reading the newline.

So you need to read in the new line values before reading the next value.

lostbard
  • 5,065
  • 1
  • 15
  • 17
-2

Try the following code by giving end limit to choice variable.

main(){
int choice;



do{
        cout<<"Enter your choice: ";
        cin>>choice; //I'm giving character i/p even though 'choice' is int
    switch(choice)
    {
        case 1:cout<<"\n 1 --\n";
               break;

        case 2:cout<<"\n 2 \n";
               break;

        case 3:cout<<"\n 3 \n";
               break;

        case 4:cout<<"\n 4 \n";
               return 0;

       default:cout<<"An Invalid choice."<<endl;

    }

}while(choice>4);

    cout<<"\n Hello";

}

The break always breaks the innermost loop.

A break statement terminates execution of the smallest enclosing switch or iteration statement.

If you want to break out of both loops, use a label and jump with goto. So basically its going into infinite loop since your break is only getting out from switch case.

Shweta Valunj
  • 148
  • 1
  • 11