为什么设置标志操纵器后位集减少? 12

问题描述

1

代码

#include<iostream>
#include<bitset>
int main()
{
    
    std::ios_base::fmtflags flag=std::ios::showpos;
    
    std::cout<<std::cout.flags()<<"\n";
    std::cout<<flag<<"\n";

    std::cout.flags(flag);
    std::cout<<std::cout.flags()<<"\n";
    
    std::cout<<59.20<<"\n";

    std::cout<<std::bitset<16>(4098)<<"\n";
    std::cout<<std::bitset<16>(2048)<<"\n";
}

输出

4098
2048
+2048
+59.2
0001000000000010
0000100000000000

看到这里我设置了 showpos 标志操纵器,然后我由 cout.flags() 返回的值(当前格式设置)减少了位设置。

2

代码

#include<iostream>
#include<bitset>
int main()
{
    
    std::cout<<std::cout.flags()<<"\n";
    
    std::cout<<std::showpos;
    std::cout<<std::cout.flags()<<"\n";
    
    std::cout<<59.20<<"\n";

    std::cout<<std::bitset<16>(4098)<<"\n";
    std::cout<<std::bitset<16>(6146)<<"\n";
}

输出

4098
+6146
+59.2
0001000000000010
0001100000000010

这里作为预期的位设置值增加1,因为我添加一个标志操纵器。

为什么当我在 cout.flags() 函数的帮助下设置标志位集减少而不是增加

解决方法

flags function 采用新值,而不是要添加的标志。您正在做的是将标志完全替换为 showpos

如果你想用flags来做,你需要自己添加标志:

std::cout.flags(std::cout.flags() | std::ios::showpos);