C++如何判斷一個string字串,是否是數字
阿新 • • 發佈:2018-12-31
方法一:判斷字元的ASCII範圍(數字的範圍為48~57)
方法二:使用C++提供的stringstream物件#include <iostream> using namespace std; bool AllisNum(string str); int main( void ) { string str1 = "wolaiqiao23"; string str2 = "1990"; if (AllisNum(str1)) { cout<<"str1 is a num"<<endl; } else { cout<<"str1 is not a num"<<endl; } if (AllisNum(str2)) { cout<<"str2 is a num"<<endl; } else { cout<<"str2 is not a num"<<endl; } cin.get(); return 0; } bool AllisNum(string str) { for (int i = 0; i < str.size(); i++) { int tmp = (int)str[i]; if (tmp >= 48 && tmp <= 57) { continue; } else { return false; } } return true; }
#include <iostream> #include <sstream> using namespace std; bool isNum(string str); int main( void ) { string str1 = "wolaiqiao23r"; string str2 = "1990"; if(isNum(str1)) { cout << "str1 is a num" << endl; } else { cout << "str1 is not a num" << endl; } if(isNum(str2)) { cout<<"str2 is a num"<<endl; } else { cout<<"str2 is not a num"<<endl; } cin.get(); return 0; } bool isNum(string str) { stringstream sin(str); double d; char c; if(!(sin >> d)) { /*解釋: sin>>t表示把sin轉換成double的變數(其實對於int和float型的都會接收), 如果轉換成功,則值為非0,如果轉換不成功就返回為0 */ return false; } if (sin >> c) { /*解釋: 此部分用於檢測錯誤輸入中,數字加字串的輸入形式(例如:34.f),在上面的的部分(sin>>t) 已經接收並轉換了輸入的數字部分,在stringstream中相應也會把那一部分給清除, 此時接收的是.f這部分,所以條件成立,返回false */ return false; } return true; }