如何在 C++ 中檢查輸入是否為數字?


我們將在本教程中瞭解如何判斷給定的輸入是數字字串還是普通字串。數字字串包含介於 0 到 9 之間的數字。這個判斷方法很簡單,我們只需要遍歷所有字元,然後逐一判斷是否是數字字元。如果是數字字元,則指向下一個字元;如果不是數字字元,則返回 false 值。

示例

#include <iostream>
using namespace std;
bool isNumeric(string str) {
   for (int i = 0; i < str.length(); i++)
      if (isdigit(str[i]) == false)
         return false; //when one non numeric value is found, return false
      return true;
}
int main() {
   string str;
   cout << "Enter a string: ";
   cin >> str;
   if (isNumeric(str))
      cout << "This is a Number" << endl;
   else
      cout << "This is not a number";
}

輸出

Enter a string: 5687
This is a Number

輸出

Enter a string: 584asS
This is not a number

更新於: 2019 年 7 月 30 日

5 千次以上觀看

開始您的 職業生涯

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.