Hello all, I'm trying to alter this code for atoi to accept an integer argument, which, if the number is larger than the length of the output string, it will insert the difference in spaces in front of the output.
For instance, if the argument is x= 15
and the output string is '24835'
then the final printed output would be 15-5 characters = 10 blank spaces inserted to the left of '24835' so it would print
24835
^^10 blank spaces
Can anyone please help? Thanks in advance. Also, if someone could please run my code on their comps and verify if my atoi function is correct and gives the correct output please.
Code:
#include<stdio.h>
#include<string.h>
/* reverse: reverse string s in place */
void reverse(char s[])
{
int c,i,j;
for(i = 0,j = strlen(s)-1; i < j; i++,j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
/* itoa: convert n to characters in s */
void itoa(int n,char s[])
{
int i,sign;
if((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate
digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while((n /= 10) > 0); /* delete it */
if(sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
int main()
{
char string[50]; /* allocate array space for 50 characters */
int x;
x = 393;
itoa(x, string);
printf("%s\n", string);
return 0;
}