我有下面的代码。我想通过将值增加一(002)来修改001的前三个字符(packet_received)。但是,当我运行代码时,会得到以下输出:

Hop_network = 001
new Hop_network = 2
packet_received = 2

我想看到的是:
收到的数据包=002456
我该怎么做?当第一个字符不是0时,代码可以正常工作,并且receid消息不必一直以0开头。谢谢你的回答。
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;
}

最佳答案

您可以使用宽度说明符sprintf左对齐数字。

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

这意味着“用零左对齐宽度3”。
所有格式说明符的文档可以在这里找到:http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

关于c - C中的整数到char数组的转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10671901/

10-13 08:20