Sunday, 29 September 2013

C++ return negative string

C++ return negative string

Hi i have the following code to convert string integer into integer, these
are the code:
#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;
}
But some how printf("%d\n", str_to_int("-5")); some how returning 5
instead -5, where am i wrong here? Thanks

No comments:

Post a Comment