写一个函数,检查字符是否是整数,如果是,返回其整数值。求高手指点一下,谢谢!

要用C++写才行

我用java写的,希望对你有用
public int atoi(String s)
{

int s_index = 0; //string index, for conversion
byte num_sign = 1; //sign of the result number
int number = 0; //result number

//check the input string length
if (s.length() <= 0)
{ System.out.println("input string length is incorrect. should be larger than 0");
return 0;
}
//System.out.println("input string is "+s);
//check the sign
if (s.charAt(0) == '-' || s.charAt(0) == '+')
{ if (s.charAt(0) == '-')
num_sign = -1;
s_index = 1;
}
for (int i=s_index; i<s.length(); i++)
{

if (s.charAt(i) >= '0' && s.charAt(i) <= '9')
{
//System.out.println("string at "+i+" is "+s.charAt(i));
number = number*10 + (s.charAt(i) - '0');

}
else {
if (s.charAt(i) != '.')
System.out.println("input string has wrong characters. should be digits 0-9");
break;
}
}
return num_sign*number;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-03-10
如果我没有理解错的话,你逐个字符判断它们的ASCII码值啊。1~9的ASCII代码是从48到57。如果该字符的ASCII码值在这个范围内,就是数字,其他的就不是。
不知道楼主要求的东西是不是这个~

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网