Return To CS 110 Home

Colour Theme   Font Size Options
 
   
   
   
Getline and Ignore

Getline and cin.ignore


Video Summary: https://youtu.be/uQdjt6qL8mw


You may notice when you are writing programs that require input that when you try to use cin after a getline statement, your program will not behave as expected. Consider the following program:


If you try and write sentences for all 3 prompts, the second getline will be skipped.

A prompt using getline
sentence one
sentence one
A prompt using cin
sentence two
sentence
A second prompt with getline
 two
Program end

This happens because cin only reads input up until the next whitespace. If there are still items in the input buffer, such as the newline character at the end of "sentence two", the next getline will not read correctly. The way to get around this is to use cin.ignore

cin.ignore, as the name implies, ignores a set amount of characters in the input stream. If you want to clear the buffer so that the next getline will work, you will want to ignore the entire buffer size. This is done with:

cin.ignore(256, '\n')

This will ignore the buffer size of 256 characters or until the next new line character is read. Thus, to fix the problem in the first program, we would write:


Which would give us the input of:

A prompt using getline
sentence one
sentence one
A prompt using cin
sentence two
sentence
A second prompt with getline
sentence three
sentence three
Program end

Notice the cin still doesn't read the entire input of "sentence two" - this is how it is supposed to work. If you are looking for a sentence, you should always use getline.

Exercise

Create a program that prompts the user for an integer age, a string first name, and a string address. Use cin.ignore to make sure the output is correct. Consider rearranging the prompts in different combinations to see where ignore is needed.

Solution