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@1201ProgramAlarmsprintf\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");