Cpp - Read and Write Characters


You can use the methods get() and put() to read or write single characters.

The get() method reads the next character from a stream and stores it in the given char variable.

char ch; 

If the character is a white space character, such as a newline, it will still be stored in the ch variable.

To prevent this from happening you can use

cin >> ch;  

to read the first non-white space character.

The get() method can be called without any arguments.

In this case, get() returns the character code of type int.

int c = cin.get(); 

The put() method can be used for unformatted output of a character.

The character to be output is passed to put() as an argument.


This statement is equivalent to cout << 'A'; , where the field width is undefined or has been set to 1.