Cpp - cin Input stream

Introduction

The >> operator, which belongs to the istream class.

It takes the current number base and field width flags into account when reading input:

  • number base specifies whether an integer will be read as a decimal, octal, or hexadecimal
  • field width specifies the maximum number of characters to be read for a string.

When reading from standard input, cin is buffered by lines.

Keyboard input is thus not read until confirmed by pressing the <Return> key.

This allows the user to press the backspace key and correct any input errors.

Input is displayed on screen by default.

The >> operator reads the next input field, converts the input by reference to the type of the supplied variable.

Any white space characters (such as blanks, tabs, and new lines) are ignored by default.

char ch; 
cin >> ch;        // Enter a character 

When the following keys are pressed

<return> <tab> <blank> <X> <return>  

the character 'X' is stored in the variable ch.

An input field is terminated by the first white space character or by the first character that cannot be processed.

int i; 
cin >> i; 

Typing 123FF<Return> stores the decimal value 123 in the variable i.

However, the characters that follow, FF and the newline character, remain in the input buffer and will be read first during the next read operation.

When reading strings, only one word is read since the first white space character will begin a new input field.

string city; 
cin >> city;     // To read just one word! 

If New York is input, only New will be written to the city string.

The number of characters to be read can be limited by specifying the field width.

For a given field width of n, a maximum of n-1 characters will be read, as one byte is required for the null character.

Any initial white space will be ignored.

Related Topics