c++ cin/getline question

Started by
4 comments, last by HeyHoHey 16 years, 11 months ago
I was just reading a different tutorial over material that i sorta know just cause i wanted to see what tutrial was better. the new one was a ton better in my mind and a lot more in depth and filled with detail and examples. instead of using cin>> x; they showed to get data by getline (cin, x); what way is the better/newer/more commonly used way? right now im used to cin>>x; i was just wondering which one i should get used to using. thanks hey
Advertisement
depends on what you are doing
with
string x;
getline(cin, x);
will get you the whole line someone types.
cin >> x; will only grab upto the first space, leaving the
rest of the line
for another cin >> x;

but with
float x;
getline(cin, x); wouldnt make sense
where
cin >> x;
does.


Now for the "getline" of a string, you may or may not want to use it. there are times when you want
the whole input from a user, and there are other times where you want to get items one at a time.

string x;
float y;
int z;
cout << "Please input [NAME] [MONEY] [ID]";
cin >> x >> y >> z;

vs.

string x;
cout >> "Please type a welcome message:";
cin << x // <-- here getline(cin,x) makes more sense.
it depends on the input. If you want to get an integer, then using the getline method would require getting the input and then converting it with a string stream. If you're getting a street address you'll need getline. Using getline for all input would allow you to spend a considerable amount of time validating the input, which could be helpful. Of course, you can do the same thing without getline and check the error state of the istream (cin) after getting input. What does this mean? It doesn't matter. In fact, since most applications being made these days are GUI based you most likely won't be using cin for input anyway.

edit: getline is probably most useful with file input depending on the file format, to be honest.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

There's also cin.get(), but I can't think of anything to say about it, haha. Anybody else?
cin.get() reads in a character at a time. It has its uses, but not as many as using getline or operator>>.
Thanks everyone after reading all of your explanations i just went to my compiler and fooled around with it. i now understand if i try to get a string of chars that has spaces with it with cin>>string; it will mess up and leave the program. when i used getline (cin, string); it worked perfectly and redisplayed it with no errors. so cin is for single things(with no spaces) and getline takes the whole thing.


ty for the help.

This topic is closed to new replies.

Advertisement