-
Doh, stupid me
<string>
using namespace std;
That worked. However, being that it has its own header file, I assumed it would work better than using a character array, but I still have the same problem.
#include <iostream>
#include <string>
int main()
{
string Name;
Name = ""
cin<<Name<<endl;
cout<<"Hello <<Name<<endl;
}
If I input Thomas, the output is:
Hello Thomas
However, if I input Thomas Anderson, the output is
Hello Thomas
How can I include spaces and such in one string?
-
~
I'm sure there's a better way to get input with the string class, but as I've never needed to, I don't know it.
Code:
#include <iostream>
#include <string>
using namespace std;
int main (void)
{
char buffer[256];
cin.getline(buffer,256);
string s(buffer);
cout << s << endl;
return 0;
}
-
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.