- In C++ input and output occurs in stream of bytes.
If the stream of sequence of bytes go from keyboard to the main memory is called as input stream.
If the stream of sequence of bytes’ flows from main memory to console display or a printer is called as output stream.
iostream header file will provide with “cin” for input operations and “cout” “cerr” “clog” for output operations. Specifically, istream provides with “cin” and ostream provides with “cout” “cerr” “clog”.
- Basic C++ input and Output:
EXAMPLE:
- Standard error:
- Standard Log
We use “clog” to display an error. “clog” is connected to standard error device. This is buffered stream. This means the log is displayed once the buffer is filled.
Example: Output:
- Type Casting with “cout”:
Typecasting is a mechanism which enables a variable of one datatype to be converted to another datatype. when a variable is typecast into a different type the compiler treats the variable as of new datatype. In the below example, shows how to typecast different data-types with cout.
Output:
- get() and put() functions:
Both of these functions are used to accept a single character and print a single character respectively.
get(): It is used to accept single character. The function has 2 variants.
- get(char*): This will assign the input character to the argument given.
- get(void): This will return the input character, so the data should be assigned to the variable on left-hand side.
put(): It is used to display a single character to output.
Example to show usage of get() and put():
Output:
Both of these functions are used to accept a single character and print a single character respectively.
get(): It is used to accept single character. The function has 2 variants.
- get(char*): This will assign the input character to the argument given.
- get(void): This will return the input character, so the data should be assigned to the variable on left-hand side.
put(): It is used to display a single character to output.
Example to show usage of get() and put():
Output:
- getline() and write():
Both of the above functions are used to read whole line from input and print a line to output.
getline function prototype:
cin.getline(variable, input_size);
write function prototype:
cout.write(variable, output_size);
EXAMPLE:
OUTPUT: