Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

c++ - "printf" on strings prints gibberish

I'm trying to print a string the following way:

int main(){
    string s("bla");
    printf("%s 
", s);
         .......
}

but all I get is this random gibberish.

Can you please explain why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because %s indicates a char*, not a std::string. Use s.c_str() or better still use, iostreams:

#include <iostream>
#include <string>

using namespace std;

int main()
{
  string s("bla");
  std::cout << s << "
";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...