C++ 字符串上的“printf”打印出乱码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3634766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"printf" on strings prints gibberish
提问by user429400
I'm trying to print a string the following way:
我正在尝试通过以下方式打印字符串:
int main(){
string s("bla");
printf("%s \n", s);
.......
}
but all I get is this random gibberish.
但我得到的只是这个随机的胡言乱语。
Can you please explain why?
你能解释一下为什么吗?
回答by Marcelo Cantos
Because %s
indicates a char*
, not a std::string
. Use s.c_str()
or better still use, iostreams:
因为%s
表示 a char*
,而不是 a std::string
。使用s.c_str()
或更好地使用,iostreams:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s("bla");
std::cout << s << "\n";
}
回答by codaddict
回答by user429400
I've managed to print the string using "cout" when I switched from :
当我从以下位置切换时,我设法使用“cout”打印了字符串:
#include <string.h>
to
到
#include <string>
I wish I would understand why it matters...
我希望我能理解为什么这很重要......
回答by user2601411
Why don't you just use
你为什么不直接使用
char s[]="bla";