2014-02-26 81 views
0

我正在创建一个程序,它将十进制值转换为二进制值。我遇到的问题是,在我的if声明中,我正在检查变量int decimal的用户输入是否包含数字,然后才转换为转换值,但是当它是数字时,它将它视为字母字符,然后导致程序无限循环。C++ - isdigit无法正常工作,导致永不结束循环

当我将isdigit(decimal)更改为!isdigit(decimal)时,转换工作正常,但如果我放入字母字符,则会再次无限循环。我在做一些非常愚蠢的事情吗?

#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(); 
} 
+0

尝试通过代码要与调试,并看看会发生什么。 – MicroVirus

+0

Dev-C++调试器不给我任何东西,它成功编译,当我做任何事情导致问题它不会返回任何东西给我 – RoyalSwish

+0

我的意思是尝试一步一步地通过调试器的代码,并看到怎么了;特别是执行流程是什么。 – MicroVirus

回答

1

首先,检查在数量和字符的混合物的数量,不占用输入到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(); 
} 

去你总是可以编写一个函数的字符串来检查数如上图所示。现在你的代码不会陷入无限循环。此外,如果你想利用只有一个有效的输入和退出程序,U可以添加一个break

if (is_num(input)) { 
    decimal = atoi(input.c_str()); 
    binary = DecToBin(decimal); 
    cout << binary << "\n"; 
    break; //<-- 
} 
+0

这工作出色,谢谢。我现在总是将输入转换为字符串数据类型以用于这些场景。我保留'while'循环,以便程序可以多次使用。 – RoyalSwish