为什么字符串连接在c ++中得到奇怪的结果?

ond*_*der -16 c++ string concatenation

我试图在C++中连接两个字符串:

"G1-2" + "-%02d.jpg"
Run Code Online (Sandbox Code Playgroud)

我得到以下结果:

G1-2-1537817269.jpg
Run Code Online (Sandbox Code Playgroud)

为什么不是这样的结果: "G1-2-%02d.jpg"

mas*_*oud 5

胡乱猜测!

您正在打印连接的字符串

printf(str);
Run Code Online (Sandbox Code Playgroud)

这里str"G1-2-%02d.jpg"

printf("G1-2-%02d.jpg");
             ^^^^
//            but, where is corresponding integer in the following?
Run Code Online (Sandbox Code Playgroud)

正如您所看到的%02d ,字符串中有一个并且printf将寻找整数参数.它找不到它并且发生了未定义的行为.在最好的情况下,它会使用字符串打印出随机值.

如果我的猜测是真的,那么尝试以这种形式打印字符串:

printf("%s",str);
Run Code Online (Sandbox Code Playgroud)

 

或使用双重%作为Chis mentined:

"G1-2-%%02d.jpg"
Run Code Online (Sandbox Code Playgroud)

  • 我希望你能找到原因,而不仅仅是症状.或者使用`puts`代替. (4认同)
  • 实际上并不错.当然`%% 02d`会修复它. (3认同)