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
In your conversion function, you skip over the -
character, because it is not in your tested range:
if (c < '0' || c > '9')
continue;
To fix it, you need to test for the -
character, and negate the value after you are done converting the value.
if (c < '0' || c > '9') {
if (c == '-' && no_other_digits_processed_yet) is_neg = true;
continue;
}
//...
if (is_neg) output = -output;
return output;
it's the if (c < '0' || c > '9') continue;
that causes this problem.
When variable c is '-', you just simply skip it. So there is no negative sign in your result.
Please just test if this number is negative (has '-') before your whole logic.
You don't really seem to account for "-" at all in your code.
You should insert some kind of hook to detect if it's a negative value:
#include <stdio.h>
int str_to_int(char* str) {
int output = 0;
char* p = str;
bool isNeg = false;
if (*p == '-')
{
isNeg = true;
p++;
}
for (int i=0;str[i]!='\0';i++) {
char c = *p++;
if (c < '0' || c > '9')
continue;
output *= 10;
output += c - '0';
}
if (isNeg)
{
output *= -1;
}
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.