一个有趣的程序:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int width = 4;
char str[20];
cout << "请输入一段文本:\n";
cin.width(5);
while (cin >> str)
{
cout.width(width++);
cout << str << endl;
cin.width(5);
}
system("pause");
return 0;
}
结果:
cout.width(4)就是输出的字符串宽度为4,不足的会用空格补足。比方说你要输出“12”,但是在输出之前用了这句话就会输出“ 12”。
cin.width(5);cin>>str;实际只能提取4个字符,str最后一个是空字符,