如何使用 C/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

更新於: 30-Jul-2019

3K+ 瀏覽量

啟動您的 職業生涯

透過完成該課程獲得認證

開始
廣告
© . All rights reserved.