在下面的代码中:
#include <string>
using namespace std;
int main(){
char command[300];
string stringz = "mystringy";
sprintf(command,"echo \"something with a string %s\" ", stringz);
system(command);
return 0;
}
为什么输出
something with a string 8�
而不是预期的
something with a string mystringy
一个愚蠢的问题,但我找不到周围的答案。
最佳答案
printf的'%s'修饰符采用char*
而不是std::string
。
你可以写:
sprintf(command,"echo \"something with a string %s\" ", stringz.c_str());
这为您提供了
const char*
到std::string
的内容。这显示了sprintf
的主要弱点之一-没有类型检查!关于c++ - 带有%s和std::string的sprintf产生乱码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31607747/