设定下次输入输出宽度,如:
int n = 8;
cout<<setw(10)<<"hello"<<setw(10)<<5<<setw(10)<<n<<endl;
参数为设定的宽度。
char name[10];
cin>>setw(9)>>name;
这样即使你输入超过9个字符,则只取9个字符。
//文件名(File Name):
LeftJustfied.cpp
//作者(Creator): water
//编译器(Compiler):Dev C++ 4.9.9.2
//日期(Date): 2007.11.25
//说明(Comment): 此程序是关于setw(n)函数的用法,可左对齐也可右对齐。
//出自:《C++ Programming: Program Design Including Data
Structure》第三章
//目的:
//输出:
#include
<iostream>
#include <iomanip>
using namespace std;
int main()
{
int a(10),
b(9876);
//set left
Justified
cout
<< left;
cout
<< "12345678901234567890"
<< endl;
cout
<< setw(6)
<< a <<
setw(7) << b
<< setw(7)
<< "water"
<< endl;
cout
<< setfill('*');
cout
<< setw(6)
<< a <<
setw(7) << b
<< setw(7)
<< "water"
<< endl;
cout
<< setw(6)
<< a <<
setw(7) <<
setfill('&') <<
b
<< setw(7)
<< "water"
<< endl;
cout
<< setw(6)
<< setfill('^')
<< a
<< setw(7)
<< setfill('%')
<< b
<< setw(7)
<< setfill('$')
<<
"water"
<< endl;
//set right
Justified
cout
<< right;
cout
<< setfill(' ');
cout
<< setw(6)
<< a <<
setw(7) << b
<< setw(7)
<< "water"
<< endl;
system("pause");
return
0;
}
http://hiphotos.baidu.com/%EF%BF%BD%EF%BF%BDe%D8%BCng%EF%BF%BD%EF%BF%BD/pic/item/8a82b901d281803f738da52a.jpg左对齐--setw(n)" TITLE="C++中 左对齐--setw(n)" />