使用 IOS 成员进行格式化
我有以下代码,只需看一下它,
#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++ 编译器)。
I have the following code, just have a look at it
#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;
}
but the first commented statement is not working for me, it also prints out 56. Am I doing a mistake, or anything else?
(I am using a visual c++,compiler).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须使用
setf
的两个参数版本,因为格式标志的基本设置不是单个位,而是使用多个位:setf
的两个参数版本code> 确保需要清除的basefield
位确实被清除。同样,您不能“取消设置”
hex
,因为它不是单个位,您必须设置不同的基数:最重要的是:请注意,在当前标准中,
的十六进制格式>ostream
仅适用于整数,不适用于浮点类型。您将需要使用或转换为整数才能查看十六进制输出。为了避免所有疑问,此代码示例按预期“工作”:
输出:
You have to use the two argument version of
setf
because the base settings of the format flags isn't a single bit, it uses a number of bits:The two parameter version of
setf
ensures thatbasefield
bits that need to be cleared are actually cleared.Similarly, you can't "unset"
hex
because it's not a single bit, you have to set a different base:Most importantly: note that in the current standard, hexadecimal formatting for
ostream
only applies to integers, not floating point types. You will need to use or cast to an integer to see a hexadecimal output.For the avoidance of all doubt this code sample "works" as expected:
Output:
尝试使用
或只是
Try using
or just