Lecture Notes - Chapter 2 - 输入输出
cin & cout
No comment is needed. The usage is simple!
Notes: always add endl
or '\n'
to your output.
Notes: formatted output is flavoured.
Caution: \t
may be dangerous
iomanip
吐槽:说实话,这玩意为啥要讲,以及为啥要现在讲……
Hard to use. In modern C++, we seldom use iomanip
.
Refer to the samples on Input/Output Manipulation when you use, and you are not required to remember all the usage/feature of each function.
Why we say, input and output is stream
Stream is defined to be a sequence(typically, a sequence of char
s), and you can only visit a stream through a position indicator.
... ... a b c ... ...
^
the position indicator
use cin >> a
, you extract some char at the position indicator and translate it into the type of a.
// input stream
... ... 123 b c ... ...
^
the position indicator
int a; cin >> a; // read the position indicator, and set `a` to 123.
// input stream
... ... 123 b c ... ...
^
the position indicator
use cout << a
, you put some char at the position indicator.
// output stream
... ...
^
the position indicator
int a = 123; cout << a; // put a into output stream.
// output stream
... ... 123
^
the position indicator
If
内嵌 if:never use in your code.
? : operator
Useful when conditionally initialize one variable:
int maximum = (a > b) ? a : b;
// Instead of
int maximum;
if (a > b) {
maximum = a;
} else {
maximum = b;
}