0

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;
}

1 Answer 1

3

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.