簡體   English   中英

isdigit()c ++,可能是簡單的問題,但卡住了

[英]isdigit() c++, probably simple question, but stuck

我在使用isdigit時遇到了麻煩。 我閱讀了文檔,但是當我cout << isdigit(9)時,我得到一個0.我不應該得到1嗎?

#include <iostream>
#include <cctype>
#include "Point.h"

int main()
{
    std::cout << isdigit(9) << isdigit(1.2) << isdigit('c');
    // create <int>i and <double>j Points
    Point<int> i(5, 4);
    Point<double> *j = new Point<double> (5.2, 3.3);

    // display i and j
    std::cout << "Point i (5, 4): " << i << '\n';
    std::cout << "Point j (5.2, 3.3): " << *j << '\n';

    // Note: need to use explicit declaration for classes
    Point<int> k;
    std::cout << "Enter Point data (e.g. number, enter, number, enter): " << '\n' 
        << "If data is valid for point, will print out new point. If not, will not "
        << "print out anything.";
    std::cin >> k;
    std::cout << k;

    delete j;
}

isdigit()用於測試字符是否為數字字符。

如果你把它稱為isdigit('9') ,它將返回非零值。

在ASCII字符集(您可能使用的)中,9表示水平制表符,它不是數字。


由於您使用I / O流進行輸入,因此無需使用isdigit()來驗證輸入。 如果從流中讀取的數據無效,則提取(即std::cin >> k )將失敗,因此如果您希望讀取int並且用戶輸入“asdf”,則提取將失敗。

如果提取失敗,則將設置流上的失敗位。 您可以測試此並處理錯誤:

std::cin >> k;
if (std::cin)
{ 
    // extraction succeeded; use the k
}
else
{
    // extraction failed; do error handling
}

請注意,提取本身也會返回流,因此您可以簡單地縮短前兩行:

if (std::cin >> k)

結果將是相同的。

isdigit()接受一個int ,它是字符的表示。 字符9是(假設您使用的是ASCII) TAB字符。 字符0x39或'9'( 不是 9)是表示數字9的實際字符。

數字字符是ASCII中的整數代碼0x30到0x39(或48到57) - 我重申,因為ASCII不是ISO C標准的要求。 因此以下代碼:

if ((c >= 0x30) && (c <= 0x39))

我之前見過的,對於可移植性來說不是一個好主意,因為至少有一個實現使用了EBCDIC - isdigit是所有情況下的最佳選擇。

isdigit()適用於您當前正在傳遞的字符,而不是ascii值。 嘗試使用isdigit('9')

暫無
暫無

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

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