Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"printf" on strings prints gibberish

Tags:

c++

string

printf

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?

like image 476
user429400 Avatar asked Sep 03 '10 10:09

user429400


3 Answers

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";
}
like image 161
Marcelo Cantos Avatar answered Nov 09 '22 13:11

Marcelo Cantos


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;
like image 27
codaddict Avatar answered Nov 09 '22 11:11

codaddict


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

like image 1
user429400 Avatar answered Nov 09 '22 13:11

user429400