3.1 C++ I/O 基本概念
C++ 的 I/O 是基于流(stream) 的概念:
流:数据从源到目的地的有序序列
流提取:
>>运算符,从流中提取数据流插入:
<<运算符,向流中插入数据
3.2 C++ I/O 对象
| 对象 | 对应流 | 说明 |
|---|---|---|
cout | stdout | 标准输出(Console OUT) |
cin | stdin | 标准输入(Console IN) |
cerr | stderr | 标准错误输出(无缓冲) |
clog | stderr | 标准错误输出(有缓冲) |
3.3 基本输入输出
xxxxxxxxxx/* iostream-basic.cpp */using namespace std;
int main() { int someInt; float someFloat; char someChar; // 输入(相当于 C 语言的 fscanf(stdin, "%d%f%c", ...)) cin >> someInt >> someFloat >> someChar; // 输出(相当于 C 语言的 fprintf(stdout, "the answer is: %f\n", ...)) cout << "the answer is: " << someInt * someFloat << endl; return 0;}运行示例:
xxxxxxxxxx输入:10 2.5 a输出:the answer is: 25
3.5 格式化输出
| 控制符 | 说明 |
|---|---|
endl | 换行并刷新缓冲区 |
dec | 十进制输出(默认) |
hex | 十六进制输出 |
oct | 八进制输出 |
left | 左对齐 |
right | 右对齐(默认) |
fixed | 定点表示法(小数形式) |
scientific | 科学计数法 |
showpoint | 显示小数点 |
noshowpoint | 不显示小数点(默认) |
showpos | 显示正号(+) |
noshowpos | 不显示正号(默认) |
noskipws | 不跳过空白字符 |
| 控制符 | 说明 |
|---|---|
setw(n) | 设置输出宽度为 n 个字符(只对下一个输出有效) |
setprecision(n) | 设置浮点数精度(默认 6 位) |
setfill(c) | 设置填充字符 |
3.5.3 格式化输出示例
xxxxxxxxxx/* iostream-format.cpp */using namespace std;
int main() { double myFloat = 123.4578; int myInt = 5; // 设置浮点数格式:定点表示 + 显示小数点 + 3 位小数 cout << fixed << showpoint << setprecision(3); // 输出标题(左对齐,宽度 10) cout << setw(10) << left << "Float"; // 输出数值(右对齐,宽度 12) cout << setw(12) << right << myFloat << endl; // 输出标题(左对齐,宽度 10) cout << setw(10) << left << "Int"; // 输出数值(右对齐,宽度 12) cout << setw(12) << right << myInt << endl; return 0;}输出结果:
xxxxxxxxxxFloat 123.458Int 5
3.5.4 更多格式化示例
xxxxxxxxxxusing namespace std;
int main() { // 十六进制输出 int num = 255; cout << hex << num << endl; // 输出:ff // 科学计数法 double d = 1234.5678; cout << scientific << d << endl; // 输出:1.235e+03 // 设置填充字符 cout << setfill('*') << setw(10) << "hello" << endl; // 输出:*****hello // 恢复默认 cout << dec << fixed << setprecision(6); return 0;}