簡體   English   中英

在C ++中,如何分辨整數和字符之間的區別?

[英]In C++ How can I tell the difference between integers and characters?

我目前正在學習C ++,有人要求我編寫一個程序,該程序將計算給定大小的存款所支付的利息。 要求之一是,當輸入非整數數據時,我們將顯示一條錯誤消息。

但是,我無法解決如何檢測是否輸入了非整數數據的問題。 如果有人能提供解決此問題的示例,將不勝感激!

您不必檢查自己。 表達式(std::cin >> YourInteger)計算結果為布爾值,且僅當成功讀取YourInteger時,才為true。 這導致成語

int YourInteger;
if (std::cin >> YourInteger) {
  std::cout << YourInteger << std::endl;
} else {
  std::cout << "Not an integer\n";
}

您需要確定輸入值是否包含非數字字符。 也就是說,除了0-9以外的任何值。

您必須首先將輸入作為字符串,然后驗證每個數字是否確實是數字。

您可以使用<cctype>定義的內置函數isdigit()來迭代字符串並測試每個字符是否為有效數字。 如果您使用的是十進制數字,則可能還需要允許一個逗號。

應該是一個足夠清晰的起點。

char* GetInt(char* str, int& n)
{
    n = 0;
    // skip over all non-digit characters
    while(*str && !isdigit(*str) )
        ++str;
    // convert all digits to an integer
    while( *str && isdigit(*str) )
    {
        n = (n * 10) + *str - '0';
        ++str;
    }
    return str;
}

暫無
暫無

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

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