Output all line with string

Hi!
I want to output the whole line with strings, not chars with the cin.get(name, 30); array. Can I do that with the #include <string> only?
Please don't use other includes since i have seen so many from the examples and they sometimes complicate things even more.
#include <string> for using strings
#include <iostream> for the output
Yes i know, i have already written #include <string> to show that i already know that way.
Here is my code with chars:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>

using namespace std;

int main()
{
	char name[100];
	cout << "Your name is: ";
	cin.getline(name, 100);
	cout << "Welcome " << name << "!";
	cin.get();
}


I want it to work with strings only
How can i do that?
Last edited on
There is a getline() that works with std::strings
http://www.cplusplus.com/reference/string/getline/
Last edited on
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>

int main()
{
	std::string name;
	std::cout << "Your name is: ";
	std::cin >> name;
	std::cout << "Welcome " << name << "!";
}
It worked only for the name, but not for the whole line
If i type in for example David Bright it will only show David
That is the whole point of using strings to get the whole name and surname

@mae
It worked for the full name. Even though i didn't exactly understood why:
1
2
3
4
5
6
7
8
9
10
11
// getline with strings
#include <iostream>
#include <string>
using namespace std;

int main () {
  string str;
  cout << "Please enter full name: ";
  getline (cin,str);
  cout << "Thank you, " << str << ".\n";
}


Why using cin as a parameter? Is not intuitive

Edit: Now i see is its parameter
Last edited on
cin stops at a space, so use this

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>

int main()
{
	std::string name;
	std::cout << "Your name is: ";
	std::getline( std::cin, name);
	std::cout << "Welcome " << name << "!";
}
Last edited on
Yes, i wrote the solution above
Thanks for replies
It takes an istream as parameter so that you can use it with other streams too, like ifstreams. Why not making it a method of istream, I don't know
There are two different versions of getline.
One looks like this, cin.getline(...), the other like this, getline(cin, ...)
http://www.cplusplus.com/reference/istream/istream/getline/
http://www.cplusplus.com/reference/string/getline/

Which one you use depends on whether you are using c-strings or c++ std::string.
Topic archived. No new replies allowed.