Question on cin.get() and cin.get(discard)

On my practice exam, I was faced with the following question:

Consider the following declaration.
char charArray[51];
char discard;

Assume that the input is:
Hello There!
How are you?

What is the value of discard after the following statements execute?

cin.get(charArray, 51);
cin.get(discard);

Choices:

Incorrect Response
a) discard = ' ' (Space)

b) discard = '!'

Correct Answer
c) discard = '\n'

d) discard = '\0'

I obviously chose "a" which was wrong and have no idea why C is the correct answer. Can someone explain "cin.get(parameter, parameter)" and "cin.get(discard)" to me?
Last edited on
cin.get(charArray, 51); will read until it finds a new line character '\n' (or the 50 char limit is reached) and the newline char is removed from the input stream. cin.get(discard); reads the next char in the input stream which is 'H' on the second line.
Last edited on
Newline character is not removed from the stream (http://www.cplusplus.com/reference/iostream/istream/get/):

istream& get (char* s, streamsize n );
Extracts characters from the stream and stores them as a c-string into the array beginning at s. Characters are extracted until either (n - 1) characters have been extracted or the delimiting character '\n' is found. The extraction also stops if the end of file is reached in the input sequence or if an error occurs during the input operation.
If the delimiting character is found, it is not extracted from the input sequence and remains as the next character to be extracted. Use getline if you want this character to be extracted (and discarded).
tfityo is right! I was wrong and I also misread the question. cin.get(charArray, 51); does leave the new line char in the input stream so the call cin.get(discard); reads the new line char into the variable discard.
Last edited on
Topic archived. No new replies allowed.