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

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

本文关键字:包含所 是否 用户 输入 整数 检查      更新时间:2023-10-16

我试图将其转换为字符串并测试字符串,但似乎找不到正确的方法来检查它并在用户输入 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;

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

尝试这样的事情:

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;