C++中cout.write使用方法

模板原型

basic_ostream& write(const char_type* s, streamsize n);

第一个参数 s: 要显示的字符串的地址
第二个参数 n: 要显示多少字符

使用cout调用write()时,将调用char具体化,因此返回类型为ostream &

下面来看一个使用的例子:

#include
#include
using namespace std;

int main()
{
	const char * state1 = "Beijing";
	const char * state2 = "Shanghai";
	const char * state3 = "Chengdu";

	int len1 = strlen(state1);
	int len2 = strlen(state2);
	cout << "Increasing loop index:\n";
	int i;
	for (i = 1; i <= len2; i++) 
		cout.write(state2, i) << endl;

	// concatenate output
	cout << "Decreasing loop index:\n";
	for (i = len2; i > 0; i--)
		cout.write(state2, i) << endl;

	// exceed string length	// 我们打印超过state1的长度看看会发现什么
	cout << "Exceeding string length:\n";
	cout.write(state1, len1 + 6) << endl;
	cout.write(state2, len2 + 5) << endl;

	system("pause");
}

C++中cout.write使用方法_第1张图片
我们发现输出的最后两行,中间隔开了最少四个字节的长度。
原因:
1.因为系统的4字节对齐方式,所以"Beijing"和"Shanghai"都占了8字节空间
2.Visual Studio或者Windows的保护设定,使每两个内容之间都存在4个字节的空余

你可能感兴趣的:(C/C++)