86

I tried this, but it didn't work.

#include <string>
string someString("This is a string.");
printf("%s\n", someString);
node ninja
  • 31,796
  • 59
  • 166
  • 254
  • 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) – ThiefMaster Mar 16 '11 at 07:32
  • Duplicate: http://stackoverflow.com/questions/3634766/c-printf-on-strings-prints-gibberish – Greg S Mar 16 '11 at 13:58

6 Answers6

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

or

printf("%s\n",someString.c_str());
metamorphosis
  • 1,972
  • 16
  • 25
GWW
  • 43,129
  • 11
  • 115
  • 108
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::.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
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;
}
hexicle
  • 2,121
  • 2
  • 24
  • 31
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())
elmout
  • 71
  • 1
3

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

#include <stdio.h>
Perry Horwich
  • 2,798
  • 3
  • 23
  • 51
-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.

Akash sharma
  • 489
  • 4
  • 5