C++ 使用sprintf追加到char数组

C++ 使用sprintf追加到char数组,c++,printf,C++,Printf,因此,这样做很有诱惑力: char buf[1024] = "this is"; std::sprintf(buf, "%s test", buf); 但这是一种未定义的行为。我想可以通过临时解决: char buf[1024] = "this is"; std::sprintf(buf, "%s test", std::string(buf).c_str()); 这种方法的缺点是什么?要将字符串附加到字符数组,请使用: 备选方案:strcpy(在本例中)sprintf(buf+strlen

因此,这样做很有诱惑力:

char buf[1024] = "this is";
std::sprintf(buf, "%s test", buf);
但这是一种未定义的行为。我想可以通过临时解决:

char buf[1024] = "this is";
std::sprintf(buf, "%s test", std::string(buf).c_str());

这种方法的缺点是什么?

要将字符串附加到字符数组,请使用:


备选方案:
strcpy
(在本例中)<代码>sprintf(buf+strlen(buf),“测试”)。您还应该考虑使用更安全的版本(<代码> Spastffs)。这是C++,您应该使用<代码> STD::String < /C> >而不是<代码> char []/Cuff>开始:<代码>字符串BUF =“这是”;buf+=“测试”@RemyLebeau为true,但由于各种原因,它必须如example@1201ProgramAlarm
sprintf\u
并不比
sprintf
更安全,也没有得到广泛的支持
snprintf
会更好option@M.M我的意思是
snprintf
,但是我想到了错误的函数名。唉。你为什么要把
“test”
转换成
char*
?或者
memmove(buf+strlen(buf),“test”,sizeof“test”)
char buf[1024] = "this is";
std::strcat(buf, " test");