简体   繁体   English

C++ sprintf 输出顺序不正确

[英]C++ sprintf output order is incorrect

I have the following code that should output;我有以下应该输出的代码;

1234 : abcd

However I get但是我得到

1234abcd : 
        char string1[4];
        sprintf(string1,"1234");

        char string2[4];
        sprintf(string2,"abcd");

        sprintf(text_string,"%s : %s",string1,string2);

How can I get the sprintf to output in the correct order?如何让 sprintf 以正确的顺序输出? I tried adding the " : " as a third string in the middle, but was still added to the end.我尝试在中间添加“:”作为第三个字符串,但仍然添加到末尾。

You have undefined behavior: The sprintf() calls both write five characters (four characters payload + one terminating null byte) to an array that is only four characters long.您有未定义的行为: sprintf()调用将五个字符(四个字符有效负载 + 一个终止空字节)写入一个只有四个字符长的数组。 After the first call to sprintf() all bets are off.在第一次调用sprintf()所有赌注都关闭了。


That said, what happens is, that the second sprintf() call overwrites the terminating null character that was written by the first sprintf() call, and thus the final sprintf() keeps printing through the second string until it finds that string's terminating null byte.也就是说,发生的情况是,第二个sprintf()调用覆盖了第一个sprintf()调用写入的终止空字符,因此最终sprintf()继续打印第二个字符串,直到找到该字符串的终止空字符字节。 I have no clue why the second string does not appear a second time in the output, but I don't have to: Since you have undefined behavior, anything is allowed to happen.我不知道为什么第二个字符串没有第二次出现在输出中,但我不必:因为你有未定义的行为,任何事情都可以发生。 Including the appearance of pink elephants...包括粉红色大象的出现……

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

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