89

I tried this, but it didn't work.

#include <string> string someString("This is a string."); printf("%s\n", someString); 
2
  • 1
    "Didn't work" - why not show us an error or what exactly didn't work? (Even though it's rather obvious in that case - but you might also have a compiler error as you don't import the std namespace) Commented Mar 16, 2011 at 7:32
  • Duplicate: stackoverflow.com/questions/3634766/… Commented Mar 16, 2011 at 13:58

6 Answers 6

155
#include <iostream> std::cout << someString << "\n"; 

or

printf("%s\n",someString.c_str()); 
Sign up to request clarification or add additional context in comments.

2 Comments

I'd always prefer the former version.
it works better: std::cout << someString << "\n";
25

You need to access the underlying buffer:

printf("%s\n", someString.c_str()); 

Or better use cout << someString << endl; (you need to #include <iostream> to use cout)

Additionally you might want to import the std namespace using using namespace std; or prefix both string and cout with std::.

Comments

13

You need #include<string> to use string AND #include<iostream> to use cin and cout. (I didn't get it when I read the answers). Here's some code which works:

#include<string> #include<iostream> using namespace std; int main() { string name; cin >> name; string message("hi"); cout << name << message; return 0; } 

Comments

7

You can't call "printf" with a std::string in parameter. The "%s" is designed for C-style string : char* or char []. In C++ you can do like that :

#include <iostream> std::cout << YourString << std::endl; 

If you absolutely want to use printf, you can use the "c_str()" method that give a char* representation of your string.

printf("%s\n",YourString.c_str()) 

Comments

3

If you'd like to use printf(), you might want to also:

#include <stdio.h> 

1 Comment

#include <cstdio>(How to print a string in C++)
-2

While using string, the best possible way to print your message is:

#include <iostream> #include <string> using namespace std; int main(){ string newInput; getline(cin, newInput); cout<<newInput; return 0; } 


this can simply do the work instead of doing the method you adopted.

2 Comments

Simply not true. The biggest flaw here is the glaring security hole (buffer overrun!) but there are others.
yupp, that was serious issue. Thanx

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.