嗨,我有以下代码将字符串整数转换为整数,这些是代码:
#include <stdio.h>
int str_to_int(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(){
printf("%d\n", str_to_int("456xy"));
printf("%d\n", str_to_int("32"));
printf("%d\n", str_to_int("-5"));
return 0;
}
但是有些printf("%d\n", str_to_int("-5"));
如何返回 5 而不是 -5,我在哪里错了?谢谢