Hi !
This is a program that i wrote to convert an integer to a string. however I came up with a problem :
The program does not work when I enter any negative number less than -999 and gives a wiered output
Can anyone help me with this and tell me why ?
I have placed ample comments in the program please let me know if still something is unclear.
The code is :
Code:#include<stdio.h> #include<string.h> void itoa(int n, char s[]) { int i = 0; /* variables to keep track of the index of the string */ int j = 0; int k = 0; int sign = n; /* variable to keep track of the sign of the integer */ int temp; /* temporary variable to store characters while reversing a string */ /* make the number positive if it is negative */ if (sign < 0) n = -n; /* run a loop and store each digit in the string ( in reverse order )*/ do { s[i++] = n%10 + '0'; } while((n/= 10) > 0); /* if the number was negative place a -ve sign at the end */ if (sign < 0) s[i++] = '-'; /* place a NULL character to mark the end of the string and bring the index marker i to the last character */ s[i] = '\0'; --i; /* loop to reverse the stirng */ for( i = 0, j = (strlen(s) - 1); i < j; i++, j--) { temp = s[i]; s[i] = s[j]; s[j] = temp; } } int main() { char s[] = ""; int n = -1000; itoa(n, s); printf("%s\n", s); return 0; }



LinkBack URL
About LinkBacks


