我正在创建一个程序,它将十进制值转换为二进制值。我遇到的问题是,在我的if语句中,我正在检查int decimal变量的用户输入在转换值之前是否包含数字,但当是数字时,它将它们视为alpha字符,这会导致程序无限循环。
当我将isdigit(decimal)更改为!isdigit(decimal)时,转换可以工作,但是如果我输入alpha字符,它将再次无限循环。我做了什么傻事吗?
#include <iostream>
#include <string>
#include <ctype.h>
#include <locale>
using namespace std;
string DecToBin(int decimal)
{
if (decimal == 0) {
return "0";
}
if (decimal == 1) {
return "1";
}
if (decimal % 2 == 0) {
return DecToBin(decimal/2) + "0";
}
else {
return DecToBin(decimal/2) + "1";
}
}
int main()
{
int decimal;
string binary;
cout << "Welcome to the Decimal to Binary converter!\n";
while (true) {
cout << "\n";
cout << "Type a Decimal number you wish to convert:\n";
cout << "\n";
cin >> decimal;
cin.ignore();
if (isdigit(decimal)) { //Is there an error with my code here?
binary = DecToBin(decimal);
cout << binary << "\n";
} else {
cout << "\n";
cout << "Please enter a number.\n";
}
}
cin.get();
}发布于 2014-02-26 12:27:16
首先,要检查数字和字符混合的数字,不要将输入输入到int中。总是和std::string一起去
int is_num(string s)
{
for (int i = 0; i < s.size(); i++)
if (!isdigit(s[i]))
return 0;
return 1;
}
int main()
{
int decimal;
string input;
string binary;
cout << "Welcome to the Decimal to Binary converter!\n";
while (true) {
cout << "\n";
cout << "Type a Decimal number you wish to convert:\n";
cout << "\n";
cin >> input;
cin.ignore();
if (is_num(input)) { //<-- user defined function
decimal = atoi(input.c_str()); //<--used C style here
binary = DecToBin(decimal);
cout << binary << "\n";
} else {
cout << "\n";
cout << "Please enter a number.\n";
}
}
cin.get();
}您可以编写一个函数来检查字符串中的数字,如上面所示。现在,您的代码不会遇到无限循环。此外,如果您只想接受一个有效的输入并退出程序,您可以添加一个break。
if (is_num(input)) {
decimal = atoi(input.c_str());
binary = DecToBin(decimal);
cout << binary << "\n";
break; //<--
}https://stackoverflow.com/questions/22040905
复制相似问题