c++中怎么判断一个string类型的字符串变量是否为数字
答案:2 mip版
解决时间 2021-01-30 21:22
- 提问者网友:谁把流年搁浅
- 2021-01-29 21:10
c++中怎么判断一个string类型的字符串变量是否为数字
最佳答案
- 二级知识专家网友:那年夏天
- 2021-01-29 22:30
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 )
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 )
全部回答
- 1楼网友:伈係鯡亼
- 2021-01-29 23:39
#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;
}
}
我要举报
如以上问答内容为低俗/色情/暴力/不良/侵权的信息,可以点下面链接进行举报,我们会做出相应处理,感谢你的支持!
点此我要举报以上问答信息
推荐资讯