which is prefferable? cinn>> or getline for string

Nov 15, 2012 at 3:19pm
closed account (DETpfSEw)
Here name, roll and cl are strings. when i use cin>> for all it dont take second input and when i use getline (cin,) for all it skip first input.
1
2
3
4
5
6
7
8
 cout<<"\n\t\t\tEnter Name: ";
                 cin>>name;
                 cout<<"\n\t\t\tEnter Roll No. ";
                 cin>>roll;
                 cout<<"\n\t\t\tEnter Class: ";
                 cin>cl;
                 cout<<"\n\t\t\tEnter number of subjects: ";
                 cin>>subjects;

i will be very thankful if you help me.
Last edited on Nov 15, 2012 at 3:20pm
Nov 15, 2012 at 3:30pm
Hmmm i think ur problem can be solved by using cin.ignore. give it a try...
Nov 15, 2012 at 3:31pm
getline will get the entire line, whitespaces included. You just need to flush your buffer before using it. That';s why it's skipping your first input.
Nov 15, 2012 at 3:31pm
closed account (DETpfSEw)
it ignore first input i think?
Nov 15, 2012 at 3:32pm
closed account (DETpfSEw)
@burhan
yar tu koi sahi HAL bta. chawlain marni bnd kr
Nov 15, 2012 at 5:00pm
Yr yehi solution ha, sachi ma. -_-
Nov 15, 2012 at 10:57pm
The getline() function reads everything, including the '\n' (which is when the user pressed the Enter/Return key).

The problem is that cin >> my_string does not read the newline, so when you next try to use getline(), you get an empty line.

Here is an old post of mine demonstrating the issue and how to correct it:
http://www.cplusplus.com/forum/beginner/20577/#msg107828

Hope this helps.
Topic archived. No new replies allowed.