嗨,有人能告诉我这段代码出了什么问题吗?
#include <stdio.h>
int convstrg(char* str) {
int output = 0;
char* p = str;
for (int i=0;str[i]!='\0';i++) {
char c = *p++;
if (c < '0' || c > '9')
continue;
output *= 10;
output += c - '0';
}
return output;
}
int main(){
char x[] = "1xx23";
printf("%d\n", convstrg(x));
return 0;
}当输出是字符串整型时,代码应该返回一个整型。但是我似乎得到了像0这样奇怪的数字。
这是几个测试用例,有些能用,有些不能用
"123" -> 123
"23xyz" -> 23
"" -> 0
"abc" -> 0
"-1" -> -1谢谢
编辑
好的,现在我整理出除了负字符串之外的所有情况。
发布于 2013-09-27 16:14:49
,
-,因此你不能期望得到正确的负数解析。您应该打破 if (c < '0' || c > '9')而不是continue。否则,从12xyz123中解析出来的值将会非常奇怪,,
std::atoi或者std::stringstream。查看here以了解更多详细信息。boost::lexical_cast这样的第三方库。https://stackoverflow.com/questions/19045813
复制相似问题