为什么cout<

时间:2014-04-08 17:03:02

标签: c++ hex cout

我有以下代码片段来打印整数的十六进制值,

int i=10;
cout<<hex<<i<<endl;

并在控制台上打印10 a的十六进制值,

但是在下一行我需要打印另一个变量的十进制值,比如

  int j=11;
  cout<<j<<endl;

但它也打印十六进制值11 b,如果我使用cout<<dec<<j<<endl;,则打印十进制值。

此外,我注意到,如果之前使用cout,则所有cout<<hex都会打印变量的十六进制值。

所以我的问题是它的正常行为?如果我之前使用<<dec一次,是否需要使用<<hex

3 个答案:

答案 0 :(得分:6)

是的,您必须使用dec才能获得cout小数值,因为hex是一个“粘性”操纵器(就像许多其他操纵器一样) - 它会留下来直到改变。

答案 1 :(得分:1)

cout是全球性的。在操纵器中移位会修改该全局的状态。鉴于你可以将操纵器链接在一起,cout的实例永远不会知道何时“取消设置”它。所以,它仍然存在。

答案 2 :(得分:1)

您可以编写自己的操纵器来克服“粘性”行为:

#include <iostream>
#include <iomanip>
#include <limits>

// Hex
// ============================================================================

template <typename T>
struct Hex
{
    enum { Width = (std::numeric_limits<T>::digits + 1) / 4 };
    const T& value;
    const int width;

    Hex(const T& value, int width = Width)
    : value(value), width(width)
    {}

    void write(std::ostream& stream) const {
        if(std::numeric_limits<T>::radix != 2) stream << value;
        else {
            std::ios_base::fmtflags flags = stream.setf(
                std::ios_base::hex, std::ios_base::basefield);
            char fill = stream.fill('0');
            stream << "0x" << std::setw(width) << value;
            stream.fill(fill);
            stream.setf(flags, std::ios_base::basefield);
        }
    }
};

template <typename T>
inline Hex<T> hex(const T& value, int width = Hex<T>::Width) {
    return Hex<T>(value, width);
}

template <typename T>
inline std::ostream& operator << (std::ostream& stream, const Hex<T>& value) {
    value.write(stream);
    return stream;
}


int main()
{
    unsigned short i = 0xa;
    std::cout << hex(i) << " == " << i << '\n';
    return 0;
}
相关问题