Somewhy the program always returns 'false'?

后端 未结 1 1979
栀梦
栀梦 2021-01-26 02:36

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          


        
相关标签:
1条回答
  • 2021-01-26 02:56

    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;
    }
    
    0 讨论(0)
提交回复
热议问题