cin problem ; skipping to next statement in C++

Posted in C/C++ LANGUAGE, PROGRAMMING by edeguzman on April 4, 2009

There was one bug I’d encountered in cin of C++, I’m not really sure whether it’s really on the cin problem but I do believe its on the cin. Below is my the sample code that I’d made to demonstrate the bug.

#include <iostream>
#define LEN 100

using namespace std;

int main ()
{
char b[LEN],c[LEN];
int x

cout<<“enter x : “; cin>>x;
cout<<“enter b : “;
cin.getline(b,len);
cout<<“enter b : “;
cin.getline(c,len);

cout<<“x = “<<<” b = “<<<” c = “<<

return 0;
}

output :

enter x : 100
enter b : enter c :

The output of the above code is not the expected output that we expect. The second statement doesn’t wait for the input of the user, it just skipped and the 3rd statement was executed.  This kind of bug only occurs when we are entering both string and integer or char data type.

I got a patch to this problem by using cin.ignore or cin.get. Below is the re-edited code with the solution to the problem.

#include <iostream>
#define len 100

using namespace std;

int main ()
{
char b[len],c[len];
int x;

cout<<“enter x : “;
cin>>x;
cin.ignore(255,’\n’);

cout<<“enter second char : “;
cin.getline(b,len);

cout<<“enter third char : “;
cin.getline(c,len);

cout<<“x = “<<x<<” b = “<<b<<” c = “<<c<<endl;

return 0;
}
The cin.ignore(255,’\n’)  statement simply clears the input buffer and ensure that the residual characters will be freed from the buffer.  This line of code should be place after the statement of getting an integer or character then proceeds with string.

The cin.get() is also an alternative to the above problem.

Advertisements

2 Responses

Subscribe to comments with RSS.

  1. atoi said, on June 22, 2013 at 8:57 pm

    Thanks, that was my problem, too!

  2. sebitafl said, on June 24, 2015 at 3:09 pm

    its not a bug, when you use cin, it ignores \n then get the information and stop just before the next \n. getline() gets a line when \n is detected and discards \n, So if you have 56\n54\n then:
    cin >> x; // process “56” leaves “\n54\n” in cin
    getline(b,cin) //process “”, leaves, discarda ‘\n’ and leaves “54\n” in cin
    getline(c,cin) //process “54”, discards \n and leaves nothing left in the input stream


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: