为什么程序总是返回'false'?

时间:2015-08-28 15:35:27

标签: c++ visual-studio visual-studio-2015

为什么这段代码总是返回'false'并激活goto,即使我输入数字?谁能帮帮我吗?谢谢!

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

1 个答案:

答案 0 :(得分:1)

如果已经处理,你只是忘了打破这种情况。 这样,在处理false案例之后,它将落入案例并处理true案例。

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

同样的问题,如果你想要阻止这个问题,请打破:

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