Marked as Duplicate
Marked as Duplicate

Reputation: 1249

Somewhy the program always returns 'false'?

Why does this code always return 'false' and activates the goto even when I type a digit? Can anyone please help me? Thank you!

char userValue = '4';
auto h = true;
tryAgain:
std::cout << "Please type a digit: ";
std::cin >> userValue;

switch (userValue) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
    h = true;
default:
    h = false;
}

switch (h) {
case true:
    std::cout << "This character is a digit.";
case false:
    std::cout << "Wrong! Try again!" << std::endl;
    goto tryAgain;
}

Upvotes: 0

Views: 72

Answers (1)

bricklore
bricklore

Reputation: 4165

You simply forgot to break out of the case if it has been processed. That way it will fall through the cases and handle the false case after the true case has been handled.

switch (h) {
case true:
    std::cout << "This character is a digit.";
break;
case false:
    std::cout << "Wrong! Try again!" << std::endl;
    goto tryAgain;

    //not necessarily needed because goto leaves the scope anyway.
    //break;
}

The same issue here, break if you wan't to stop the fallthrough:

switch (userValue) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
    h = true;
    break;

default:
    h = false;
    break;
}

Upvotes: 1

Related Questions