int myatoi(const char* string) {
int i;
i = 0;
while(*string) {
i = (i << 3) + (i<<1) + (*string -'0');
string++;
}
return i;
}
int main() {
int i = myatoi("10101");
printf("%d\n",i);
char a = (char)(((int)'0')+i);
printf("%c\n",a);
return 0;
}
my output turns out to be
10101
�
how to fix this
should I parse int by int to convert into a char because we can use any c built in functions that can help us convert
What do you expect to have happen?
Your code correctly converts the string
"10101"into the integer10101, and prints it. That looks fine. You then compute10101+(int)'0'which is probably 10149 (in ascii or unicode,(int)'0'is 48). Converting that to acharprobably gives you 165 (or perhaps -91) which probably doesn’t correspond to a printable character on your system, so you get a blank/garbage/missing character.All is as expected.