Code:
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string userInput;
string Greeting("Hello ");
cout << "Please enter your name: ";
getline(cin, userInput);
Greeting += userInput;
cout << Greeting << endl;
return 0;
}
You can use the "+=" operator (or the "+" operator), with strings to concatenate strings.
Code:
#include <iostream>
#include <string>
int main()
{
string Name;
Name = ""
cin<<Name<<endl;
cout<<"Hello <<Name<<endl;
}
Your code does not compile - You need to include a "using namespace std;" after including the iostream header. There is a ; missing from your assignment to Name. << is not appropriate for cin objects - it should be >> . You also have not closed off the last cout statement.
The reason that you are getting the behaviour your seeing is that cin's default behaviour is to read only up until the first whitespace. The rest of your input is still sitting in the input buffer.. i.e. if you where to do this:
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string Name; // For user input
string Cleanup; // Cleanup what is in the buffer
cout << "Please enter both names: "; // ask for the users input
cin >> Name; // Only text up to the first whitespace
// is stored in Name
cout << "First name: " << Name << endl;
cin >> Cleanup; // The next call to cin places what is left
// in the input buffer into string Cleanup
cout << "This is the second name: " << Cleanup << endl;
}
So, if you are looking to get input for more than one word at a time, it is more appropriate to use the getline() method.
NOTE: This is not the best way of removing unwanted data in the input buffer. Lookup the ignore() method.