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;
}
If you'd like to use printf()
, you might want to also:
#include <stdio.h>
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.
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())
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::
.
Source: Stackoverflow.com