简体   繁体   English

C中的整数到char数组的转换

[英]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 ). 我想通过将值增加一个( 002 )来修改packet_received的前三个字符( 001 )。 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 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. 当第一个字符不是0且收据消息不必始终以0开头时,该代码可以正常工作。 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;
}

You can use the width specifier to sprintf to left-justify the number. 您可以使用宽度说明符对sprintf左对齐数字。

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

This means "left-justify with zeroes to width 3". 这意味着“用零左对齐到宽度3”。

The documentation for all format-specifiers can be found here: http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/ 可以在以下位置找到所有格式说明符的文档: http : //www.cplusplus.com/reference/clibrary/cstdio/sprintf/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM