dimanche 27 janvier 2019

Checking if a user entered integer contains all 1's or 0's?

I've tried to convert it to a string and test the string, but can't seem to find the right way to check it and re-prompt the user if they enter something other than a 1 or 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;

}

Aucun commentaire:

Enregistrer un commentaire