C++ 程式來檢查輸入是整數還是字串


由使用者給出的輸入,任務是檢查該輸入是整數還是字串。

整數可以是 0 到 9 之間的任何數字組合,而字串可以是除了 0 到 9 之外的任何組合。

示例

Input-: 123
Output-: 123 is an integer
Input-: Tutorials Point
Output-: Tutorials Point is a string

下面使用的方法如下

演算法

Start
Step 1->declare function to check if number or string
   bool check_number(string str)
   Loop For int i = 0 and i < str.length() and i++
      If (isdigit(str[i]) == false)
         return false
      End
   End
   return true
step 2->Int main()
   set string str = "sunidhi"
      IF (check_number(str))
         Print " is an integer"
      End
      Else
         Print " is a string"
      End
      Set string str1 = "1234"
         IF (check_number(str1))
            Print " is an integer"
         End
         Else
            Print " is a string"
         End
Stop

示例

#include <iostream>
using namespace std;
//check if number or string
bool check_number(string str) {
   for (int i = 0; i < str.length(); i++)
   if (isdigit(str[i]) == false)
      return false;
      return true;
}
int main() {
   string str = "sunidhi";
   if (check_number(str))
      cout<<str<< " is an integer"<<endl;
   else
      cout<<str<< " is a string"<<endl;
      string str1 = "1234";
   if (check_number(str1))
      cout<<str1<< " is an integer";
   else
      cout<<str1<< " is a string";
}

輸出

sunidhi is a string
1234 is an integer

更新日期: 02-11-2023

40K+ 次觀看

開啟你的 事業

完成課程並獲得認證

開始
廣告
© . All rights reserved.