Mohamed

Beyond the borders of sanity

C++ problem with getline after cin

When people get bored, they usually do something fun. When I get bored, I write a new blog post.

So yesterday, I was working on an assignment which was a C++ program. I had code similar to this:

#include<iostream>
 using namespace std;

int main()
{
	char x[10];
	int y;

	cout<<"Enter a number";
	cin>>y;
	cout<<"Enter a string";
	cin.getline(x,9);

	system("PAUSE");
}

Okay, so its pretty simple. I'm asking for a integer from the keyboard, and then i need a char[]. I'm using "getline" because I wanted to count spaces as well.

Should have worked ... but it didn't:

problem

After I enter the number and press ENTER, it doesn't ask me for the next input.

ZOMG what happened! Why does it skip the.getline and terminate the program? That question kept haunting me for a while... Until I found out why. I found the answer on this site called mathbits

So it turns out that the "cin" input steam function ignored the trailing "\n" in the input stream ...

The getline on the other hand, keeps reading until it FINDS a "\n" ... See how that works?

Since the previous "Cin" kept a trailing "\n", the getline found it and thought it was the end of the input!

 Solution

The solution is well presented on mathbits as well.

plan A

One solution is to use cin.ignore(100,'\n'). This ignores up to a 100 characters in the stream, until it meets a "\n" .

#include<iostream>
 using namespace std;

int main()
{
	char x[10];
	int y;

	cout<<"Enter a number: ";
	cin>>y;
	cout<<"Enter a string: ";
	cin.ignore(100,'\n');//!!!!!!!!!!!!!!!!!!!//
	cin.getline(x,9);

	system("PAUSE");
}
Plan B

Another solution is to use a dummy string variable to absorb the nasty \n :

#include<iostream>;
using namespace std;

int main()
{
	char x[10];
	char dummy[2]; //!!!!!!!!!!!!!!!!!!!!!!//
	int y;

	cout<<"Enter a number: ";
	cin>>y;
	cout<<"Enter a string: ";
	cin.getline(dummy,1); //!!!!!!!!!!!!!!!!!!!!//
	cin.getline(x,9);
	cout<<x;
	system("PAUSE"&quot;");

}

Well done! You have now managed to overcome the \n getline problem.

← Back


The people have spoken


comments powered by Disqus