C++输入流
输出流基本概念
输出流定义在
使用输出流的最简单的方法是使用<<运算符。通过<<可以输出C++的基本类型,例如int、指针、double和字符串。此外,C++的string类也兼容<<,C风格的字符串也能正常输出。
int i = 7;
cout << i << endl;
char ch = 'a';
cout << ch << endl;
string str = "hello world !";
cout << str << endl;
C++流可以正确地解析C风格的转义字符,例如包含\n的字符串,也可以使用std::endl开始一个新行。\n和endl的区别是,\n仅仅开始一个新行,而endl还会刷新缓存区。使用endl要小心,因为过多的刷新缓存区会降低性能。
输出流的方法
put()和write()
put()和write()是原始的输出方法。put()接受单个字符,write()接受一个字符数组。
flush()
向流写入数据时,流不一定会将数据立即写入目标。大部分输出流都会进行缓存,也就是积累数据,而不是立即将得到的数据写出去。当满足一下条件之一是,流进行刷新操作(flush):
- 达到某个标记时,例如endl标记
- 流离开作用域被析构时。
- 要求从对应的输入流输入数据时(即要求从cin输入时,cout会刷新)。
- 流缓存满时。
显示要求刷新缓存的方法是调用flush()方法。
cout << "abc";
cout.flush(); // abc is written to the console.
cout << "def";
cout.endl; // def is written to the console.
并不是所有的输出流都会缓存,例如cerr流就不会缓存
处理输出错误
- 当一个流处于正常的可用状态时,称这个流是好的。调用good()方法可以判断这个流当前是否处于正常状态。
- good()可以获得流的基本验证信息,但是不能提供流不可用的原因。bad()方法提供稍多的信息。如果bad()返回true,意味着发生了致命的错误。另一个方法fail()在最近一次操作失败时返回true,但是没有说明下一次操作是否也会失败。
cout.flush();
if(cout.fail()){
cerr << "Unable to flush to standard out. " << endl;
}
- 通过clear()方法可以重置流的错误状态
输出操作算子
流的一项独特性是,放入数据滑槽的内容并非仅限于数据,C++流还能识别操作算子,操作算子是能够修改流行为的对象,而不是流能够操作的数据。大部分的操作算子定义在
- boolalpha和noboolalpha:要求流将bool值输出为true和false或1和0.
- hex、oct和dec:分别十六进制、八进制和十进制输出数字。
- setprecision:设置输出小数时小数位数。这是一个参数化的操作算子(也就是说这个操作算子接受一个参数)。
- setw:设置输出数据的字段宽度。这是一个参数化操作算子。
- setfill:当数字宽度小数指定宽度时,设置用于填充的字符。
- showpoint和noshowpoint:对于不带小数部分的浮点数,强制要求显示或是不显示小数点。
- put_money:向流写入一个格式化的货币。
- put_time:向流写入一个格式化的时间值。
- quoted:把给定的字符串封装在引号中,并转义嵌入引号。这个是一个参数化的操作算子。
// boolean values
bool myBool = true;
cout << "This is the default: " << myBool << endl;
cout << "This should be true: " << boolalpha << myBool << endl;
cout << "This should be 1: " << noboolalpha << myBool << endl;
// Money amount
cout << "This should be a money amount of 120000, formatted according to your location: "<< put_money("120000") << endl;
// Date and time
time_t t_t = time(nullptr); // Get current system time.
tm* t = localtime(&t_t); // Convert to local time.
cout << "This should be the current date and time formatted according to your location: " << put_time(t,"%c") << endl;
// C++14 : Quoted string
cout << "This should be \"Quoted string with \\\"embedded quotes\\\".\" :" << quoted("Quoted string with \" embedded quotes\".") << endl;