Somewhy the program always returns 'false'?

Marked as Duplicate

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;
}
bricklore

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;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related