簡體   English   中英

C++:檢查它是否是類中的數字

[英]c++ : check if it is a Number in class

在這段代碼中,我想知道兩個數字是 Int 還是 String :

#include <iostream>
using namespace std;

class calculate{
    private:
        bool checkNumbers(int num1, int num2){
            if(isdigit(num1) && isdigit(num2)){
                return true;
            }else{
                return false;
            }
        }

public:
    void sum(int x, int y){
        bool chek=checkNumbers(x, y);
        if(chek==true){
            cout<< "yes it is Number"<< endl;
        }else{
            cout<< "Nope! String"<<endl;
        }
    }
};

int main()
{
    calculate calulate;
    calulate.sum(3, 2);
    return 0;
}

但是在運行代碼后,我只看到不! String ,這意味着它是字符串。 誰知道出了什么問題? 我用isdigit檢查了數字,我只發送了兩個數字

calulate.sum(3, 2);

但什么都沒有!! 謝謝

您的問題在於您使用std::isdigit(int)

該函數旨在檢查int是否等效於 10 個以char表示的十進制數字之一, 0123456789 但是,此函數僅適用於 48-57 的int值。

int應為char的整數值。 如果您希望它解析為true ,請使用 48-57,其中480491 ,等等...

請注意,如果您向函數傳遞了一個char例如“3”),則您的函數自然會解析為 true,就像一位評論者所說的那樣。 這是因為char(3) == int(51)

例如:

isdigit('1'); // This is true, because '1' is a "char" digit
isdigit(49); // This is true

isdigit(1); // This is false
isdigit(60); // This is false

num1num2std::isdigit解釋為字符。 通常這意味着ASCII 字符

並且作為 ASCII 字符 2 和 3 是控制字符而不是數字,它們的范圍是 '0' (0x30) 到 '9' (0x39)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM