"printf" on strings prints gibberish

21,989

Solution 1

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

Solution 2

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;

Solution 3

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...

Share:
21,989
user429400
Author by

user429400

Updated on December 26, 2020

Comments

  • user429400
    user429400 over 3 years

    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?