c++ - 使用IOS成员(member)进行格式化

标签 c++ iostream

我有下面的代码,看看吧

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;

int main()
{
    float a=56;
    cout.setf(ios::hex);

    cout<<"\nyou have entered "<<a;/*this statement must output a value in hexadecimal*/
    _getch();
    cout.unsetf(ios::hex);
    cout<<"\n modified value"<<a; /*& it should give me an answer 56*/

    _getch();
    return 0;
}

但是第一个注释语句对我不起作用,它也打印出 56。我是在做错什么,还是其他什么?
(我使用的是 Visual C++ 编译器)。

最佳答案

您必须使用 setf 的两个参数版本,因为格式标志的基本设置不是单个位,它使用多个位:

std::cout.setf( std::ios_base::hex, std::ios_base::basefield );

setf 的两个参数版本确保实际清除需要清除的basefield 位。

同样,您不能“取消设置”hex,因为它不是一位,您必须设置不同的基数:

std::cout.setf( std::ios_base::dec, std::ios_base::basefield );

最重要的是:请注意,在当前标准中,ostream 的十六进制格式仅适用于整数,不适用于浮点类型。您需要使用或转换为整数才能看到十六进制输出。

为避免所有疑问,此代码示例按预期“工作”:

#include <iostream>
#include <ostream>

int main()
{
    int a = 56;
    std::cout.setf( std::ios_base::hex, std::ios_base::basefield );
    std::cout << "Hex: " << a << '\n';
    std::cout.setf( std::ios_base::dec, std::ios_base::basefield );
    std::cout << "Dec: " << a << '\n';
    return 0;
}

输出:

Hex: 38
Dec: 56

关于c++ - 使用IOS成员(member)进行格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7007054/

相关文章:

c++ - 移动构造函数和赋值运算符 : why no default for derived classes?

python - 停止嵌入式 python

c++ - 带捕获的比较器

C++从单词的开头删除非字母字符

c++ - 带有颜色和标题的 std::clog 包装器无法正确打印整数

c++ - OpenGL 中的像素操作

C++重载->,它是如何工作的?

c++ - 通用打印功能

c++ - 难以为文件处理类重载运算符<<

c++ - 为什么 iostream::eof 在循环条件(即 `while (!stream.eof())` )内被认为是错误的?