C++判断是不是数字的两种方法,可以判断正负数,小数。
#include#include using namespace std; bool isNum(string str); bool isNumber(const string& str); int main(void) { string str1 = "-255332"; string str2 = "-1990.2363"; if (isNum(str1)) { cout << "str1 is a num" << endl; } else { cout << "str1 is not a num" << endl; } if (isNumber(str2)) { cout << "str2 is a num" << endl; } else { cout << "str2 is not a num" << endl; } cin.get(); return 0; } bool isNumber(const string& str) { return str.find_first_not_of("-0123456789.") == string::npos; } bool isNum(string str) { stringstream sin(str); double d; char c; if (!(sin >> d)) { return false; } if (sin >> c) { return false; } return true; }



