0

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

Hop_network = 001 
new Hop_network = 2 
packet_received = 2 

我想看到的是:

packet_received = 002456

我该怎么做?当第一个字符不是 0 时,该代码可以正常工作,并且接收消息不必一直以 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;
}
4

1 回答 1

3

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

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

这意味着“用零左对齐到宽度 3”。

所有格式说明符的文档都可以在这里找到:http ://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

于 2012-05-20T08:23:20.433 回答