2014-02-26 82 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