I was trying to write my own implementation of the atoi()
function, and tried two different codes:
#include <stdio.h>
#include <string.h>
int myatoi(const char *string);
int main(int argc, char* argv[])
{
printf("\n%d\n", myatoi("str"));
getch();
return(0);
}
int myatoi(const char *string){
int i;
i=0;
while(*string)
{
i=(i<<3) + (i<<1) + (*string - '0');
string++;
// Don't increment i!
}
return i;
}
And
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int x;
gets(str);
printf("%d",myatoi(str));
}
int myatoi(char *str) {
int res =0;
int i;
for (i = 0; str[i]!= '\0';i++) {
res = res*10 + str[i] - '0';
}
return res;
}
Both these cases work fine for input e.g. 1999.
But if by chance I am passing user input e.g. "abcd", it is returning some numeric value. I tried it with the original atoi()
and it returns 0 for such cases.
Can someone please explain to me how to handle non-numeric input through atoi()
.
You should use isdigit()
to see if the next character is a (decimal) digit or not, and stop when it fails.
You also need to check for, and handle, leading minus sign(s) to indicate a negative number. Not sure if e.g. --12
is valid with atoi()
or not, probably not.
Also please don't micro-optimize multiplies like that, it's not the 90s any more. :)