std::cout <<"Info: Starting...\n";
std::cerr <<"ERROR: File not found!\n";
std::clog <<"LOG: User logged in\n";
五、输出流的成员函数
函数
功能
示例
operator<<
插入数据
cout << x;
put()
输出单个字符
cout.put('A');
write()
输出原始字节
cout.write(buf, n);
flush()
强制刷新缓冲区
cout.flush();
seekp()
设置写位置(文件流)
file.seekp(0);
tellp()
获取当前写位置
auto pos = file.tellp();
六、格式控制(<iomanip>)—— 核心!
操纵符
作用
示例
std::endl
换行 + 刷新
cout << endl;
std::flush
强制刷新
cout << flush;
std::setw(n)
设置字段宽度
cout << setw(10) << x;
std::setfill(c)
填充字符
cout << setfill('0');
std::left / std::right / std::internal
对齐方式
cout << left;
std::hex / std::dec / std::oct
进制
cout << hex << 255; → ff
std::showbase
显示进制前缀
0xff, 077
std::boolalpha
true/false
cout << boolalpha << true;
std::fixed
固定小数点
3.14
std::scientific
科学计数法
3.140000e+00
std::setprecision(n)
精度
setprecision(2)
示例:格式化表格
#include<iostream>#include<iomanip>usingnamespace std;cout << left <<setw(15)<<"Name"<< right <<setw(10)<<"Age"<<setw(12)<<"Salary"<< endl;cout <<setfill('-')<<setw(37)<<""<<setfill(' ')<< endl;cout << left <<setw(15)<<"Alice"<< right <<setw(10)<<25<<setw(12)<< fixed <<setprecision(2)<<50000.50<< endl;
输出:
Name Age Salary
-------------------------------------
Alice 25 50000.50