johan
johan

Reputation: 1983

integer to char array conversion in C

I have the code below. I would like to modify the first three characters (001) of packet_received by increasing the value by one (002). However, I get the following output when I run the code:

Hop_network = 001 
new Hop_network = 2 
packet_received = 2 

what I would like to see is:

packet_received = 002456

How can I do it? The code works fine when the first characters are not 0s, and the receid message does not have to start with 0s all the time. Thank you for the answers.

int main(int argc,char *argv[]){
    char Hop_network[4];
    char packet_received[]= "001456";
    int Hop_increaser;

    Hop_network[0] = packet_received[0];
    Hop_network[1] = packet_received[1];
    Hop_network[2] = packet_received[2];
    Hop_network[3] = '\0';
    printf("Hop_network = %s\n", Hop_network);

    Hop_increaser = atoi(Hop_network);
    Hop_increaser = Hop_increaser + 1;
    sprintf(Hop_network, "%d", Hop_increaser);
    printf("new Hop_network = %s\n", Hop_network);

    packet_received[0] = Hop_network[0];
    packet_received[1] = Hop_network[1];
    packet_received[2] = Hop_network[2];
    printf("packet_received = %s\n", packet_received);
    return 0;
}

Upvotes: 0

Views: 923

Answers (1)

Hampus Nilsson
Hampus Nilsson

Reputation: 6822

You can use the width specifier to sprintf to left-justify the number.

sprintf(Hop_network, "%03d", Hop_increaser);

This means "left-justify with zeroes to width 3".

The documentation for all format-specifiers can be found here: http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

Upvotes: 3

Related Questions