C++判斷用戶輸入是否爲數字?


#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
 bool is_number(string str)
  {
     if(str.c_str()[0]!=45)
     {
        for(int i = 0; i < str.length(); i++)
        {
           if( str.c_str()[i] < '0' || str.c_str()[i] > '9' )
           { return false;}
         }
        return true;
     }
     else
     {
       for(int i = 1; i < str.length(); i++)
        {
           if( str.c_str()[i] < '0' || str.c_str()[i] > '9' )
           { return false;}
        }
       return true;
     }
 }
void main()
{ int a=0;
  const char *s;
  cout<<"請輸入數據a:";
  string str;
  cin>>str;
  if(is_number(str))
  {
    cout<<"你輸入的是數字!"<<endl;
    s=str.c_str();
    a=atoi(s);
    a=a+1;
    cout<<"a+1="<<a<<endl;
  }
  else cout<<"你輸入的不是數字!";
}


一次性獲取用戶當前輸入(他輸入的可能是1位數也可能是2位數或者字母等)並判斷是否爲嚴格意義上的數字,主要是爲了區分數字和字母。如果不是數字則返回重輸,如果是,使用該int 型數據做其他操作。

主要思路是採用string類的成員函數c_str()實現。對於成功判斷是數字以後如果要使用該數字可以再調用atoi(const char*s)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章