嗨,有人能指出我这段代码有什么问题吗?
#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
谢谢
编辑
好的,现在我整理出所有预期为负字符串的情况..
最佳答案
- 您永远不会检查前导字符是否为
-
因此,您不能指望正确解析负数。 - 你应该打破
if (c < '0' || c > '9')
而不是继续。否则来自12xyz123
的解析值会很奇怪。 - 我希望您知道有内置函数可以从字符串中解析整数,例如使用
std::atoi
或使用std::stringstream
.看看here了解更多详情。 - 您还可以使用第三方库,例如
boost::lexical_cast
像这样boost::lexical_cast<int>(x)
关于C++整理负输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19045813/