检查用户输入的整数是否包含所有 1 或 0?
Checking if a user entered integer contains all 1's or 0's?
我试图将其转换为字符串并测试字符串,但似乎找不到正确的方法来检查它并在用户输入 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
。
0
和1
int
。'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;
相关文章:
- 是否需要删除包含对象的"pair"?
- 在CMake中使用find_package时,是否会显式包含标头
- C++-字符串是否包含一个带有简单循环的单词
- 我是否需要包含隐式使用/与 WindowsAPI 通信"Windows.h"?
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- Gtkmm 会不断检查 Gtk::日历上的所选日期是否发生变化
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- 是否存在包含负号的isdigit函数(过载)
- 检查路径是否包含C++中的另一个路径
- C++ - 是否可以让子类按值包含包含类?
- C++17:使用 std::optional 来评估枚举是否包含值
- 在头文件上包含 cpp 文件是否有缺点?
- 如果包含映射的静态库与可执行文件和动态库链接,静态映射(变量)是否会被多次释放?
- 如何检查 int 变量是否包含合法(非陷阱表示)值?
- 如果我从流中提取某些内容,该流是否不再包含我提取的内容?
- 如何确定integer_sequence在编译时是否包含给定的数字?
- 调用包含所有所需代码的函数或内部包含所需代码的其他函数的函数更好?
- 使一个标头成为多个类包含所必需的
- 包含后是否需要前瞻声明
- 创建一个类,其静态成员容器包含所述类的所有实例