标准流对象分别负责什么
C++ 用统一流接口处理控制台、文件等 I/O。常用标准流都来自 <iostream>:

| 流对象 | 描述 |
|---|---|
cin | 标准输入流 |
cout | 标准输出流 |
cerr | 标准错误输出流 |
clog | 日志输出流 |
常用状态检查:good()、fail()、bad()、eof()。
#include <iostream>
int main() {
int number;
std::cout << "输入一个数字:";
std::cin >> number;
std::cout << "你输入的是:" << number << std::endl;
std::cerr << "这是一条错误消息" << std::endl;
return 0;
}
输入输出怎么写得更稳妥
std::cin >> 会按目标类型解析。按字符、整行、二进制块读取时可用 get()、getline()、read()。

关键是处理失败输入:先 clear(),再 ignore() 丢弃无效内容。
#include <iostream>
#include <limits>
int main() {
int input;
while (!(std::cin >> input)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "输入无效。请重试:";
}
return 0;
}
文件流接口风格一致:
#include <fstream>
#include <iostream>
int main() {
std::ofstream outFile("example.txt");
outFile << "在LabEx环境中写入文件" << std::endl;
outFile.close();
return 0;
}
常用流操纵符有哪些
常见操纵符分为进制、精度、对齐和输入空白控制。

#include <iostream>
#include <iomanip>
int main() {
int value = 42;
double pi = 3.14159265358979;
std::cout << std::hex << value << std::endl;
std::cout << std::dec << value << std::endl;
std::cout << std::oct << value << std::endl;
std::cout << std::fixed << std::setprecision(2) << pi << std::endl;
std::cout << std::scientific << pi << std::endl;
std::cout << std::right << std::setw(10) << std::setfill('*') << 42 << std::endl;
std::cout << std::left << std::setw(10) << "LabEx" << std::endl;
std::cout << std::boolalpha << true << std::endl;
return 0;
}
| 操纵符 | 作用 |
|---|---|
dec/hex/oct | 切换进制 |
fixed/scientific/setprecision() | 控制浮点格式与精度 |
setw()、left、right、setfill() | 控制宽度与对齐 |
boolalpha | 输出 true/false |
skipws、noskipws、ws | 控制空白字符处理 |
写标准流代码时的实用建议
先区分 cout、cerr、clog 的用途;关键读取后检查状态;输入失败时及时 clear() 与 ignore();统一格式优先用操纵符;文件流用完关闭;浮点输出明确精度。









