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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:20:19  来源:igfitidea点击:

"printf" on strings prints gibberish

c++stringprintf

提问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 %sindicates 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

You need to use c_strto get c-string equivalent to the string content as printfdoes not know how to print a string object.

您需要使用c_str来获取与字符串内容等效的 c 字符串,因为printf不知道如何打印字符串对象。

string s("bla");
printf("%s \n", s.c_str());

Instead you can just do:

相反,您可以这样做:

string s("bla");
std::cout<<s;

回答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";