注册 登录
编程论坛 C++教室

setw 操纵元问题,高手请进! ! ! ! ! ! !

zyc19911109 发布于 2010-04-04 16:20, 351 次点击
大家先来看一下这个代码:
#include<iostream>
#include<iomanip>

int main()
{
    using namespace std;
   
    cout.setf(ios::right);
    cout.width(5);
    cout << 123 << "*" << endl;
    cout << 123 << "*" << endl;
    cout.width(5);
    cout << 123 << "*" << endl;

    cout.setf(ios::left);
    cout << setw(5) << 123 << "*" << endl;
    cout << 123 << "*" << endl;
    cout << setw(5) << 123 << "*" << endl;
   
    cout.setf(ios::right);
    cout << setw(5) << 123 << "*" << endl;
    cout << 123 << "*" << endl;
    cout << setw(5) << 123 << "*" << endl;
   
    return 0;
}
这是结果:
  123*
123*
  123*
  123*
123*
  123*
  123*
123*
  123*

为什么会出现这种结果呢?cout.setf(ios::left)不是应该将 setw 操纵元设置成 左对齐,右补空格 的状态吗?
大家再把:
    cout.setf(ios::right);
    cout.width(5);
    cout << 123 << "*" << endl;
    cout << 123 << "*" << endl;
    cout.width(5);
    cout << 123 << "*" << endl;
删掉看看,删掉之后,好像就行了。这又是为什么呢?

这是结果的图:
只有本站会员才能查看附件,请 登录
2 回复
#2
lijm19892010-04-04 23:02
注意用cout.setf()设置输出的格式后,换别的先用cout.unsetf()取消先前格式。试试。。
#3
zyc199111092010-04-05 11:18
可以了,谢了
1