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?
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"; } 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; 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...
include to include ? What do you mean ?