"printf" on strings prints gibberish

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";
}

I've managed to print the string using "cout" when I switched from :

#include <string.h>

to

#include <string>

I wish I would understand why it matters...


You need to use c_str to get c-string equivalent to the string content as printf does not know how to print a string object.

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

Instead you can just do:

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

Tags:

C++

String

Printf