What is the difference between these cin functions?

Explanations
The function cin.fail() returns true if the failure bit is set in the cin stream.

The expression cin >> will ignore spaces then attempt to read in the data type. If the read fails, the cin status will be set to failure. There is an overload that allows the return value of operator>> to be converted from failure to bool.

The expression cin.get() != '\n', reads in a character from cin, then tests that character for newline ('\n'). Note: the character read from cin is deleted and not available for other purposes.

The expressions are used for different purposes.

Usages

  • cin.fail() — to test the failure state of cin, after something
    has been read from cin.
  • cin >> — reads in an object from cin, using formatted input
    (e.g. converting textual number to internal format). May be
    overloaded for other objects.
  • cin.get() != '\n' — Used when searching for a newline. The
    character read is trashed after the comparison.

Leave a Comment