大众信息网

c++中怎么判断一个string类型的字符串变量是否为数字

关注:273  答案:2  手机版
解决时间 2021-01-30 21:22
c++中怎么判断一个string类型的字符串变量是否为数字
最佳答案
c库提供了一些函数,可以用来判断一个字符是不是数字。不过并没有提供用来判断一个字符串的函数。所以你需要自己遍历字符串,用ctype库提供的函数来判断字符串中的每一个字符。很简单事,一个循环就可以。
ctype提供的函数有:
isalnum
Check if character is alphanumeric (function )
isalpha
Check if character is alphabetic (function )
isblank 
Check if character is blank (function )
iscntrl
Check if character is a control character (function )
isdigit
Check if character is decimal digit (function )
isgraph
Check if character has graphical representation (function )
islower
Check if character is lowercase letter (function )
isprint
Check if character is printable (function )
ispunct
Check if character is a punctuation character (function )
isspace
Check if character is a white-space (function )
isupper
Check if character is uppercase letter (function )
isxdigit
Check if character is hexadecimal digit (function )
全部回答
#include #include #include using namespace std; bool isnum(string s) { stringstream sin(s); double t; char p; if(!(sin >> t)) return false; if(sin >> p) return false; else return true; } int main() { string s; while(cin >> s) { if(isnum(s)) cout << s << " is a number." << endl; else cout << s << " is not a number." << endl; } }
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!