How to print a string in C++
C++StringPrintfC++ Problem Overview
I tried this, but it didn't work.
#include <string>
string someString("This is a string.");
printf("%s\n", someString);
C++ Solutions
Solution 1 - C++
#include <iostream>
std::cout << someString << "\n";
or
printf("%s\n",someString.c_str());
Solution 2 - C++
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::
.
Solution 3 - C++
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;
}
Solution 4 - C++
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())
Solution 5 - C++
If you'd like to use printf()
, you might want to also:
#include <stdio.h>
Solution 6 - C++
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.