C++中把数据之间的传输操作称为流。C++的流是通过重载运算符 “<<” 和 “>>” 执行输入和输出操作。输出操作是向流中插入一个字符序列,因此,在流操作中,将左移运算符 “<<” 称为插入运算符。输入操作是从流中提取一个字符序列,因此,将右移运算符“>>” 称为提取运算符。
1、cout
cout 代表显示器,执行 cout << x 操作就相当于把 x 的值输出到显示器。
2、cin
cin 代表键盘,执行 cin >> x 就相当于把键盘输入的数据赋值给变量。
3、流操作的控制
C++在头文件 iomanip.h 中定义了一些控制流输出格式的函数,默认情况下整型数按十进制形式输出,也可以通过hex将其设置为十六进制输出。
常用的流操作控制函数:
(1) long setf(long f);
(2) long unself(long f);
(3) int width();
(4) int width(int w);
(5) setiosflags(long f);
(6) resetiosflags(long f);
(7) setfill(int c);
(8) setprecision(int n);
(9) setw(int w);
常用的数据输入/输出的格式控制操作符:
(1) dec:转换为十进制输出整数,也是默认格式。
(2) oct: 转换为八进制输出整数。
(3) hex: 转换为十六进制输出整数。
(4) ws: 从输出流中读取空白字符。
(5) endl: 输出换行符 \n 并刷新流。
(6) ends: 输出一个空字符\0。
(7) flush: 只刷新一个输出流。
4、示例
(1) 输出大写的十六进制
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
int i = 0x2F, j = 255;
cout << i << endl;
cout << hex << i << endl;
cout << hex << j << endl;
cout << hex << setiosflags(ios::uppercase) << j << endl;
return 0;
}
输出结果:
(2) 控制打印格式程序
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
double a = 123.456789012345;
cout << a << endl;
cout << setprecision(9) << a << endl;
cout << setprecision(6); //恢复默认格式(精度为6)
cout << setiosflags(ios::fixed);
cout << setiosflags(ios::fixed) << setprecision(8) << a << endl;
cout << setiosflags(ios::scientific) << a << endl;
cout << setiosflags(ios::scientific) << setprecision(4) << a << endl;
return 0;
}
输出结果:
(3) 控制输出精确度
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
int x = 123;
double y = -3.1415;
cout << "x=";
cout.width(10);
cout << x << endl;
cout << "y=";
cout.width(10);
cout << y << endl;
cout.setf(ios::left);
cout << "x=";
cout.width(10);
cout << x << endl;
cout << "y=";
cout << y << endl;
cout.fill('*');
cout.precision(4);
cout.setf(ios::showpos);
cout << "x=";
cout.width(10);
cout << x << endl;
cout << "y=";
cout.width(10);
cout << y << endl;
return 0;
}
输出结果:
(4) 流输出小数控制
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
float x = 20, y = -400.00;
cout << x << ' ' << y << endl;
cout.setf(ios::showpoint); //强制显示小数点和无效0
cout << x << ' ' << y << endl;
cout.unsetf(ios::showpoint);
cout.setf(ios::scientific); //设置按科学表示法输出
cout << x << ' ' << y << endl;
cout.setf(ios::fixed); //设置按定点表示法输出
cout << x << ' ' << y << endl;
return 0;
}
输出结果:
5、printf
c++ 中还保留着C 语言中的屏幕输出函数 printf。使用方法一样