16

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?

4 Answers 4

29

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"; } 
Sign up to request clarification or add additional context in comments.

3 Comments

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?
I've amended the code to be self-contained and compilable (and tested).
19

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; 

4 Comments

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.
Oh, Ok, it makes sense:) Thank you.
1

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

3 Comments

From include to include ? What do you mean ?
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.)
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++.
-2

Why don't you just use

char s[]="bla"; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.