-
cin.getline()
i have written this code for a phone directory for entering data of 5 persons when i use "cin>>" then my program works but when i use cin.getline then my program does not works
after one menu it does not repeat menu for input just display messages 4 times simultaneaously
Code:
# include <iostream>
# include <conio.h>
using namespace std;
struct directory
{
long int phone_number;
char name[50];
};//end struct
int main ()
{
directory a[5];
for (int i=1;i<=5;i++)
{
cout<<"enter name of a person: "<<endl;
cin.getline(a[i].name,50);
cout<<"enter phone number of person: "<<endl;
cin>>a[i].phone_number;
}//end for
getch ();
}//end main
-
cin skips initial white-space and newlines, reads some input, then stops at white-space and newlines (and leaves them in the input stream).
getline() reads everything, and specifically stops at newlines.
Mixing the two usually ends up in grief.
Itīs generally a good idea to adopt a single, consistent approach to reading input.
-
-
I generally agree with Salem, but unfortunately the more elegant solutions are all relatively complicated.
A simple solution to this issue is to add cin.ignore(); on the line directly after reading in the phone number. This ignores the newline entered when the user types the phone number and hits <enter>. (You do not want to add ignore() after the call to getline, because getline ignores that newline automatically.)
-
can u give me some example how to "cin" ?
-
I'm not sure what you mean? Your code is using cin right now.
-
i mean to say i cant understand what salem is saying i cant abstract something from his words
kindly salem give me some example
-
cin gives you multiple ways to do the same thing with its data. The data it actually has are usually things that you type. It's text.
Salem is saying that it is OK to use this method to extract data:
cin>>a[i].phone_number;
You can do that with any type C++ has built in already and it will turn into what you want automagically. If this is the only way you used throughout the program, it would work. It's the same deal with getline(). If you relied on getline() it would work. While using getline() (in effect, reading strings) is elegant, Daved has also commented that it's complicated.
What he means by this is that the strings you read need to be converted into ints or floats or whatever you have.
How do you do that? Well it's a FAQ, and we all know that nobody reads those. Just like they hardly search for their question on the boards. :(