带有%s和std :: string的sprintf产生乱码 [英] sprintf with %s and std::string gives gibberish
本文介绍了带有%s和std :: string的sprintf产生乱码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在以下代码中:
#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
一个愚蠢的问题,但我找不到答案.
A silly question, but I couldn't find an answer around.
推荐答案
printf的'%s'修饰符使用 char *
,而不是 std :: string
The '%s' modifier of printf takes a char*
, not a std::string
.
您可以写:
sprintf(command,"echo \"something with a string %s\" ", stringz.c_str());
哪个为 std :: string
的内容提供了 const char *
.这显示了 sprintf
的主要弱点之一-没有类型检查!
Which gives you a const char*
to the contents of a std::string
. This shows one of the major weaknesses of sprintf
-- no type checking!
这篇关于带有%s和std :: string的sprintf产生乱码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文