-
Problem with cin.getline
Here's what is shown:
Code:
Input name: John Mendez
Input newvar1: 2
Input newvar2: 5
Input newvar3: 1
Input name: Input newvar1: 5
Input newvar2: 3
Input newvar3: 8
Press any key to continue. . .
My program isn't allowing me to input a name a second time via getline.
May someone please help?
Here's code:
Code:
void addperson(char name[40][20],int&newvar1,int&newvar2,int&newvar3,slot)
{
cout<<"Input name: ";
cin.getline(name[slot],20); //Problem is here
cout<<"Input newvar1: ";
cin>>newvar1[slot];
cout<<"Input newvar2: ";
cin>>newvar2[slot];
//etc
slot++;
}
char choice()
{
char tchoice;
cin>>tchoice;
return tchoice;
}
void main()
{
char name[40][20];
int newvar1[40],newvar2[40],newvar3[40],slot=0;
do addperson(name,newvar1,newvar2,newvar3,slot);
while (choice()=='Y');
}
-
This is most likely the standard problem of not emptying the cin buffer. Try not to mix calls to operator>> with calls to getline(). Things get all out of sync, as you see here.
-
The getline function reads from the input buffer until it sees a newline character, at which point it removes that character and stops.
This works the first time around. However, cin>> does things a little different. It skips all whitespace (spaces, tabs, newlines) and then reads in the value and stops.
What is happening is that after the user types 2 they hit <enter> which leaves a newline in the stream. This is fine here, because cin>>newvar2[slot] will skip over that newline when it reads in the 5. Similarly, cin >> newvar2[slot] will skip the newline that came after 5 and then read in 1.
Now, the next time through, the newline that came when the user hit <enter> after typing 1 is still there. The getline functions sees this but does not skip it. Instead it thinks it is done, so it stops.
One solution is to ignore the trailing newline when you use cin>> to read in values. That means adding cin.ignore(); after each call to cin>> (or at least the ones that come before getline). Don't put cin.ignore() after getline because getline already removes that final newline character.
-
Thanks Daved again - you've been really helpful.
-
More helpful tips for you: you should learn to indent your code (makes it easier to read, helps find bugs) and not use void main because it's undefined. Use int main.