为什么会输出乱码??

wyget 2011-04-20 08:36:54
string s("hello")
printf("%s", s);

为什么会是乱码?那怎样打印string类型
...全文
119 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
luciferisnotsatan 2011-04-22
  • 打赏
  • 举报
回复
printf("%s", s.c_str());
qq675927952 2011-04-22
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 happymawolf 的回复:]
C/C++ code
#include <iostream>
#include <string>
using namespace std;

int main(void)
{
string s("hello");
printf("%s", s.c_str());

return 0;
}

要用char数组,参考printf参数
[/Quote]

正解;
或者你直接 cout<<s<<endl;也行
gaara777 2011-04-22
  • 打赏
  • 举报
回复
应该不会出现乱码。。。
qufeng1 2011-04-20
  • 打赏
  • 举报
回复
printf("%s", s.c_str());
乱在长安 2011-04-20
  • 打赏
  • 举报
回复
直接用COUT就行了。S是string的对象。
子达如何 2011-04-20
  • 打赏
  • 举报
回复
.c_str()
lijiancsu123 2011-04-20
  • 打赏
  • 举报
回复
printf参数的原型为:
_CRTIMP int __cdecl printf(const char *, ...);
当格式符为"%s"时,后面的输出部分应该为char *型,
s.c_str()正好返回的是char *型,
所以正确的写法是:
printf("%s", s.c_str());
书虫 2011-04-20
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>
using namespace std;

int main(void)
{
string s("hello");
printf("%s", s.c_str());

return 0;
}

要用char数组,参考printf参数
书虫 2011-04-20
  • 打赏
  • 举报
回复
少了个分号
string s("hello");
printf("%s", s);

64,636

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧