-
getline problem
Hey guys,
I have some code in a program which does the following:
Code:
char a[20];
cout<<"enter a word"<<endl;
cin.getline(a, 20);
But for some reason the getline code gets ignored. I was just wondering if anyone knows whys its getting ignored?
-
I was able to solve the problem by adding cin.ignore(); before my cin.getline() i don't understand why this works, does anyone else? Thanks
-
Are you using MSVC? MSVC 6 has a bug in getline() which causes it to not work.
If you are using MSVC, either get Dev-C++ or use cin>> or write your own function or something like that.
-
Thanks for your reply, I am using MSVC6 is the cin.ignore the correct way to avoid the problem I have come accross?
Thanks.
-
This is discussed in the FAQ here
If you look around the forum you'll see that this is an issue that
comes up a lot in C/C++. I'd say everyone gets thrown by it
at some point unless its pointed out to them first.
-
The FAQ doesn't say anything about MSVC's bug.
-
what i meant was flushing the input buffer, mixing input functions
generally leaves junk in the buffer that needs to be flushed.
I probably should have been more specific, figured that 182 hadn't
encountered it before.
-
Thanks for the replies, is the cin.ignore() the correct way to solve this problem?
-
What you are describing looks less like the getline bug and more like a typical problem where the input stream contains a newline character left over from a previous input operation. This situation commonly comes in instance such as the following:
Code:
int number;
char a[20];
cout << "Enter a number: ";
cin >> number;
cout << "Enter a word: ";
cin.getline(a,sizeof a);
In the above code fragment, the cin >> number line will read an integer from the user and leave the trailing newline character in the input buffer. The unread newline will then get eaten by the getline below causing the user to think the program skipped/ignored that line of code. The correct way to deal with this is to call cin.ignore prior to any getline command that comes after a cin >> line.
That said, you should take a look a this page for a list of fixes that can be applied by making some small changes to your headers to make sure you don't actually come up against the getline bug. As explained by that page, the getline bug actually affects the string version of the getline function and not the version you are using.