Alex Rivera | Logout

"printf" on strings prints gibberish

Asked 2010-09-03T10:12:45.047
16

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?

Edit
Report

1 Answer

29

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 << "\n";
}
answered 2010-09-03T10:16:21.843

Your Answer