首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ -等位数不能正常工作并导致永续循环

C++ -等位数不能正常工作并导致永续循环
EN

Stack Overflow用户
提问于 2014-02-26 12:08:47
回答 1查看 1.2K关注 0票数 0

我正在创建一个程序,它将十进制值转换为二进制值。我遇到的问题是,在我的if语句中,我正在检查int decimal变量的用户输入在转换值之前是否包含数字,但当是数字时,它将它们视为alpha字符,这会导致程序无限循环。

当我将isdigit(decimal)更改为!isdigit(decimal)时,转换可以工作,但是如果我输入alpha字符,它将再次无限循环。我做了什么傻事吗?

代码语言:javascript
复制
#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();
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-26 12:27:16

首先,要检查数字和字符混合的数字,不要将输入输入到int中。总是和std::string一起去

代码语言:javascript
复制
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

代码语言:javascript
复制
if (is_num(input)) {
    decimal = atoi(input.c_str()); 
    binary = DecToBin(decimal);
    cout << binary << "\n";
    break; //<--
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22040905

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档