C中的整数到字符数组转换

时间:2012-05-20 08:20:23

标签: c arrays integer char

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

Hop_network = 001 
new Hop_network = 2 
packet_received = 2 

我希望看到的是:

  

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

1 个答案:

答案 0 :(得分:3)

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

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

这意味着“左对齐零,宽度为3”。

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