Data Input and Output

I/O Streams

In C++, the flow of data from one object to another is abstracted as “streams”. cin and cout are predefined stream class objects, where cin is used to handle standard input (keyboard input), and cout is used to handle standard output (screen output).


Predefined Insertion and Extraction Operators

“<<” is the predefined insertion operator, which when applied to the stream class object cout can achieve the most general screen output.

“>>” is the extraction operator, which when applied to the stream class object cin can achieve the most general keyboard input.


Common I/O Stream Library Manipulators

Manipulator Name Meaning
dec Numeric data in decimal representation
hex Numeric data in hexadecimal representation
oct Numeric data in octal representation
ws Extract whitespace characters
endl Insert newline and flush the stream
setsprecision(int) Set decimal places for floating point numbers (including decimal point)
setw(int) Set field width

if-else Statements

First, the pairing method of else is to pair with the if at the same level by looking upward. For example:

1
2
3
4
5
6
if()
if()
else()
else
if()
else()

This is feasible because all else statements have pairs, but indentation does not represent structure. Strictly speaking, {} should be used to distinguish different nesting levels. Only for distinguishing different structures.


Counter-example:

1
2
3
if()
if()
else

In this case, else pairs with the indented if.


typedef Declaration

typedef existing_type_name new_type_name_list

For example:

1
2
3
4
5
typedef double Area,Volume;
typedef int Natural;
Natural i1,i2;
Area a;
Volume v;

Another Way to Define Custom Types Besides typedef: using

using new_type_name = existing_type_name

For example:

1
2
using Area = double;
using Volume = double;

auto Type and decltype Type

auto: The compiler automatically determines the variable type through the initial value decltype: Define a variable with the same type as a certain expression, but do not initialize the variable with that expression For example: decltype(i) j = 2; makes j have the same type as i, but does not initialize j with 2.