一些I/O类
out.wirte
//===============================================================
//FileName:
// write.cpp
//Date:
// 2019/11/30
//Author:
// khoing(https://blog.csdn.net/qq_45391763)
//===============================================================
//using cout.write()
#include <iostream>
int main() {
using std::cout;
using std::endl;
const char* state1 = "Florida";
const char* state2 = "Kansas";
const char* state3 = "Euphoria";
//------------------------------------------------------------------------
int len = std::strlen(state2);
cout << "Increasing loop index:\n";
int i;
for (i = 1; i <= len; i++)
{
cout.write(state2, i);//第一个参数指出要显示的字符串的地址,第二个参数指出要显示多少个字符
cout << endl;
}
//------------------------------------------------------------------------
// concatenate output
cout << "Decreasing loop index:\n";
for (i = len; i > 0; i--)
cout.write(state2, i) << endl;//cout.write返回cout对象,所以可以拼接
//------------------------------------------------------------------------
// exceed string length
cout << "Exceeding string length:\n";
cout.write(state2, len + 5) << endl;
//write方法并不会遇到空字符时自动停止打印字符,而只是打印指定数目的字符。
//即使超过了字符串的边界!
//超过后打印相邻的内存中的数据。
return 0;
}
刷新输出缓冲区
- 由于ostream类对cout对象处理的输出进行缓冲,所以输出不会立即发送到目标地址,而是被存储到缓冲区中,直到缓冲区填满,然后程序将刷新(flush)缓冲区,把内容发送出去,并清空缓冲区,以存储新的数据,通常,缓冲区为512字节或其整数倍,当标准输出连接的是硬盘上的文件时,缓冲可以节省大量的时间。
- 对于屏幕输入
float num;
cout<<"Enter a number: ";
cin >> num;
- 假设没这种特性,程序将等待输入,而无法通过cout消息来提示用户。
- 如果实现不能在所希望时刷新输出,可以使用两个控制符中的一个来强行进行刷新。
- endl 和flush可以强行进行刷新缓冲区
float num;
cout<<"Enter a number: "<<flush;
//或者
flush(cout);
//其实cout<<flush;就是重载以了以上 的方法
//或者
cout<<"Enter a number: "<<flush;//刷新加换行符
cin >> num;
cout进行格式化
//===============================================================
//FileName:
// defaults.cpp
//Date:
// 2019/11/30
//Author:
// khoing(https://blog.csdn.net/qq_45391763)
//===============================================================
//cout default formats
#include <iostream>
int main() {
using std::cout;
cout << "12345678901234567890\n";
//------------------------------------------------------------------------
char ch = 'K';
int t = 273;
//------------------------------------------------------------------------
cout << ch << ":\n";
cout << t << ":\n";
cout << -t << ":\n";
//------------------------------------------------------------------------
double f1 = 1.200;
cout << f1 << ":\n";
cout << (f1 + 1.0 / 9.0) << ":\n";
//------------------------------------------------------------------------
double f2 = 1.67E2;
cout << f2 << ":\n";
f2 += 1.0 / 9.0;
//------------------------------------------------------------------------
cout << f2 << ":\n";
cout << (f2 * 1.0e4) << ":\n";