tags:

views:

216

answers:

3

Hi,

Sorry about the simple question - I'm a newby (obviously):

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?

Thanks, Li

+7  A: 

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;
codaddict
Thank... btw - why? printf does not know how to handle strings?Is there another method I can use?
I've tried it with std::cout and the compiler issues an error: binary '<<' : no operator found which takes a right-hand operand of type 'std::string'
printf does not know how to handle c++ std::string s, it works on c strings(array of char with \0 to mark the end of string), note that because of backwards compatibility c++ c++ string literals, ie just "bla" instead of string s("bla") are c strings and not objects of the c++ std::string class.
Roman A. Taycher
Oh, Ok, it makes sense:) Thank you.
+11  A: 

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";
}
Marcelo Cantos
I've tried it with std::cout and the compiler issues an error: binary '<<' : no operator found which takes a right-hand operand of type 'std::string'
That's very strange. Which C++ implementation is this?
pjc50
I've amended the code to be self-contained and compilable (and tested).
Marcelo Cantos
It works for me!
Chubsdad
A: 

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

I think this comment has been mangled?
pjc50
From `include` to `include` ? What do you mean ?
Cedric H.
SO was mangling his comment, I fixed it by adding the #s.
egrunin
The answer source included the data that Markdown removed. (BTW, @lazygoldenpanda, please don't post answers for things that should be comments or edits to the original question.)
bk1e
string.h is a standard C header. Headers for most C++ standard library items don't have a .h To access standard C headers in C++ code you should prefix a 'c'. e.g. <cstdlib> instead of <stdlib.h>. This is the intent of the C++ standards body to try to keep things non-colliding between C and C++.
Digikata