Subscribe Now: standard

Tuesday, October 18, 2011

[SOLUTION] gets or cin.getline skipping input


Welcome in tech wizards and witches.

Today we will try and solve a very simple but irritating problem that nearly every programmer that has tried his hand in c++ has faced.

The gets() or cin.getline() range of functions are found to jump a input statement and continue onto the next line without taking input.
So why does this happen? Why does the program seem to skip a input statement and jump onto the next line. The reason for this is the string terminating character \0  and the difference in how gets() and cin.getline() work.

Any string is terminated by the '\0' character. When a string is entered through the keyboard the data first enters a buffer which stores the values.

So if i am entering the string "HELLO" the buffer will look like HELLO\0  (where each color represent a memory slot)

When we are using gets to get the string it takes the entire group including the \0 from the buffer and keep the buffer clean.

BUT

When we are using cin it leaves the \0 behind in the buffer making it \0              

So when gets or cin.getline look for string the next time it immediately encounter the \0 and think the string is over, so it skips the input.

SOLUTION
To solve this you have to first identify where this happens.
Then just above the gets or cin.getline statement there enter the following command:
cin.ignore()
 This will solve the problem.

WARNING!
ONLY USE AT PLACES WHERE THERE IS THE JUMPING PROBLEM. 
Do not give the cin.ignore() function above every input statement.
Doing so will cause you to loose the first character of the input in places where you were not facing the skipping problem as it will ignore the first character of the input.

That's all folks

Till next time Good Bye

No comments:

Post a Comment