Hello all,

I have been trying to use swtich cases in conditions but it won't work

what I mean is like this;

do{
cout<<"Enter a valid number";
cin>>number;

switch(number)
{
case 0: bla bla
break;
case 1: bla bla
break;
case default: cout<<"re-enter";
}
}while(defalut);


if that can never happen .. what is a good effcient way of accomplishing the same task

Thanks in advance

Dani AI

Generated

A few quick clarifications and a robust way to handle the input problem.

As found, you cannot use a case label as a loop condition. The switch is a statement and default is just a label inside it. The correct pattern — suggested by , and — is to use a separate boolean/flag to control the loop and set that flag inside the case branches (set true for valid choices, false in default).

The infinite loop on character input happens because cin >> number fails on non-numeric tokens: the stream sets its failbit and the bad token stays in the buffer, so the next extraction fails immediately. Recover by clearing the stream state and removing the bad input, for example with cin.clear() and cin.ignore(...) (see and std::istream::ignore).

For a more robust approach, read a full line with std::getline and then parse it. On modern compilers prefer std::from_chars (no exceptions) (std::from_chars); if unavailable use std::stoi/strtol with proper error checks. When checking characters with std::isdigit, always cast to unsigned char to avoid undefined behavior (std::isdigit).

Recommended Answers

All 7 Replies

It works just fine:

#include <iostream>

using std::cout;
using std::cin;

int main()
{
    bool again = true;

    do
    {
        cout << "Enter a digit between 0 & 1: ";
        int i;
        cin >> i;

        switch (i)
        {
            case (0):
               cout << "You chose 0\n";
               again = false;
               break;
            case (1):
                cout << "You chose 1\n";
                again = false;
                break;
            default:
              cout << "Wrong choice...\n";
        };
    } while (again);

    return 0;
}

Hey,

You're declaring default wrong, and just need to use an overall boolean while.

int number;
bool valid = false;
do{
cout<<"Enter a valid number ";
cin >> number;

switch(number)
{
case 0: 
	cout << "0 \n";
	valid = true;
	break;
case 1: 
	cout << "1 \n";
	valid = true;
	break;
default: 
	cout << "You Fail \n";
	valid = false;
	break;
}
}while(valid == false);

Should work for any number (Chars will break it, but as you didn't say anything, assuming only numbers)

Thanks Lilly

ps. Oops looks like I was beaten while typing >.<

You can't use an actual case statement from a switch as a conditional. The cases are linked to the switch structure. You will need to use some other value or a flag of some sort.

bool validInput;

do{
  validInput = true;   //assume input is valid until invalid input detected
  cout<<"Enter a valid number";
  cin>>number;

  switch(number)
  {
    case 0:
      /* ... bla bla; ... */
      break;
    case 1:
      /* ... bla bla; ... */
      break;
    default:
      cout<<"re-enter";
      validInput = false;
  }
} while(!validInput);

ouch, double ninja'd

Thank you both.. that's an excellent way

now regarding char as Lilal pointed out.. is an issue it self

I did a do.. while loop it works just fine when entering a number but it does and infinate loop if the input was a charcter .. how can I over come this?

Thank you both.. that's an excellent way

now regarding char as Lilal pointed out.. is an issue it self

I did a do.. while loop it works just fine when entering a number but it does and infinate loop if the input was a charcter .. how can I over come this?

Take it in as a string not int, Do an "if isDigit" then cast to int, else ignore it. :P Funs.

Lilly

thank you too Fbody for the explanation..

can you contribute to the solving of the infinate loop issue "when using charcters" in the do.. while

Take it in as a string not int, Do an "if isDigit" then cast to int, else ignore it

okay I got the part about taking it as a string but how do i make sure it is a digit to avoid casting a digit again ..
and by ignoring what do you exactly mean

cheers
:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.