检查用户输入的整数是否包含全1或0?

时间:2019-01-28 00:59:37

标签: c++ c++11

我曾尝试将其转换为字符串并测试该字符串,但似乎找不到正确的方法来检查它并重新提示用户(如果他们输入的不是1或0)。

int binNum, decNum = 0, i = 0, remainderAmount;
string testString;

cout << "Enter a binary number: ";
cin >> binNum;
testString = to_string(binNum);
for (int i = 0; i < testString.length(); i++)
{
    while (testString[i] != 1 && testString[i] != 0)
    {
        cout << "Please enter a valid binary number: ";
        cin >> binNum;
        testString = to_string(binNum);
    }
}

cout << "Binary number: " << binNum << " is ";

while (binNum != 0)
{
    // Check if remainder is 0 or 1
    remainderAmount = binNum % 10;
    // Remove the last digit from the binary number
    binNum /= 10;
    // Get first decimal number
    decNum += remainderAmount*pow(2,i);
    // Increment the place for the binary power i
    i++;
}

cout << decNum << " in decimal" << endl;
cout << endl;

2 个答案:

答案 0 :(得分:2)

testString[i]char,而不是int

01int

'0''1'char

整数0与字符'0'不同(十六进制0x30,十进制48)。

整数1与字符'1'(十六进制0x31,十进制49)不同。

这就是为什么您的while无法正常工作的原因。

此外,每次您提示用户输入新的输入字符串时,您都不会从该字符串的开头重新进行测试。您正在从先前输入错误的地方开始的相同索引处开始。每次提示用户时,您都需要重新测试完整的输入。

尝试更多类似的方法:

bool isValid(int num) {
    string testString = to_string(num);
    for (int i = 0; i < testString.length(); i++) {
        if (testString[i] != '1' && testString[i] != '0')
            return false;
    }
    return true;

    /* alternatively:
    return (to_string(num).find_first_not_of("01") == string::npos);
    */
}

...

cout << "Enter a binary number: ";
do {
    if (cin >> binNum) {
        if (isValid(binNum)) {
            break;
        }
    } else {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');    
    }
    cout << "Please enter a valid binary number: ";
}
while (true);

答案 1 :(得分:-1)

尝试这样的事情:

int binNum, decNum = 0, i = 0, remainderAmount;
bool error = false;

int n;

cout << "Enter a binary number: ";  

do
{

    cin >> binNum;

    n = binNum;
    error = false;
    i = 0;
    decNum = 0;

    while (binNum != 0)
    {

        // Check if remainder is 0 or 1
        remainderAmount = binNum % 10;

        if(remainderAmount & -2)
        {
            cout << "Please enter a valid binary number: ";

            error = true;
            break;
        }

        // Remove the last digit from the binary number
        binNum /= 10;
        // Get first decimal number
        decNum += remainderAmount*pow(2,i);
        // Increment the place for the binary power i
        i++;
    }

}
while(error);

cout << "Binary number: " << n << " is ";

cout << decNum << " in decimal" << endl;
cout << endl;