0

This is probably going to be embarrassing, but here we go! I have the following code (shown below), and it is suppose to take an int and convert it to an char string. (I know about itoa() and snprintf, but I wan't to make it work like this.) Everything seem's to work fine until I try to print it and it displays nothing for the inttochar string. It's probably just something stupid I've overlooked... I get the following result:

CHAR1: 4334321
CHAR2: 1234334
CHAR3: 

The code is here:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(){
int tester = 1234334;   //Test value
char temp[10];          //Temporary string array.       
char inttochar[10];         
int t = 0;

//Reads int to array.
while(tester != 0){
    temp[t] = (tester % 10) + '0';
    tester /= 10;
    t++;    
}
temp[t] = '\0';
t = 0;
printf("CHAR1: %s\nCHAR2: ",temp);


//Reverses the string.
for(int j=strlen(temp); j>=0;j--){
    inttochar[t] = temp[j];
    printf("%c",inttochar[t]);
    t++;
}
inttochar[t] = '\0';
t = 0;
printf("\nCHAR3: %s\n",inttochar);
} 
4

3 回答 3

1
t=0;
for(int j=strlen(temp); j>=0;j--){
    inttochar[t] = temp[j];
    t++;
    }
inttochar[t] = '\0';

Is off by one. A "better" (does not need j to be signed) way to write this loop would be:

t=0; 
for(size_t j=strlen(temp); j-- > 0;){
    inttochar[t++] = temp[j];
    }
inttochar[t] = '\0';
于 2012-05-12T13:33:08.183 回答
1

You should start from j=strlen(temp)-1, otherwise you assign \0 (which is what's in temp[strlen(temp)]) to inttochar[0].

于 2012-05-12T13:33:17.040 回答
1

Reverse iteration using a for-loop is easier like this:

for(int j=strlen(temp); j--; ){
    inttochar[t] = temp[j];
    printf("%c",inttochar[t]);
    t++;
}

Note the test-and-decrement in one.

This can be applied to reverse iteration in general.

于 2012-05-12T13:40:48.010 回答