在C/C++中判断string是否是一个数值类型

levin_zhang 2001-10-26 12:58:43
如何在C/C++中判断string是否是一个数值类型呢?
Java中使用异常机制即可实现:
public boolean checkDecimal(String value)
{
boolean result = false;
try
{
Double tmpDouble = new Double(value);
result = true;
}
catch ( NumberFormatException nfe )
{
System.out.println(value + " is not a valid Decimal Type ");
}
return result;
}
不知道C/C++如何实现,请指教,谢谢。
...全文
367 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ajiefudan 2001-10-26
  • 打赏
  • 举报
回复
不好意思,自己没用过,没想到阿没想到,这atoi这么牛,hehe,:-)]
那就自己用第一种办法写一个?
levin_zhang 2001-10-26
  • 打赏
  • 举报
回复
MSDN上的例子:
#include <stdlib.h>
#include <stdio.h>

void main( void )
{
char *s; double x; int i; long l;

s = " -2309.12E-15"; /* Test of atof */
x = atof( s );
printf( "atof test: ASCII string: %s\tfloat: %e\n", s, x );

s = "7.8912654773d210"; /* Test of atof */
x = atof( s );
printf( "atof test: ASCII string: %s\tfloat: %e\n", s, x );

s = " -9885 pigs"; /* Test of atoi */
i = atoi( s );
printf( "atoi test: ASCII string: %s\t\tinteger: %d\n", s, i );

s = "98854 dollars"; /* Test of atol */
l = atol( s );
printf( "atol test: ASCII string: %s\t\tlong: %ld\n", s, l );
}


Output

atof test: ASCII string: -2309.12E-15 float: -2.309120e-012
atof test: ASCII string: 7.8912654773d210 float: 7.891265e+210
atoi test: ASCII string: -9885 pigs integer: -9885
atol test: ASCII string: 98854 dollars long: 98854

string中含有pigs...也会返回一个数值的。
所以,atoi, atof如果都没错,那它就一定是数值么?
ajiefudan 2001-10-26
  • 打赏
  • 举报
回复
方法一:
一个字节一个字节的比较,判断字符的ASCI码值是否在 '0'---'9',+ - . E e等范围内,如果是,那就是数值。
方法二:
调用atoi,atof,如果两个函数都有错,那就不是数值

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧