cout.setf(ios::hex)等设置进制输出为什么没效果?

kanonayu 2007-07-26 11:02:46
#include<iostream>
#include <iomanip>
using namespace std;
int main()
{
cout.setf(ios::showbase);
cout<<hex<<2123<<endl;
system("pause");
return 0;
}

这样的话可以转换进制的输出,但是换到下面的就没效果。

#include<iostream>
#include <iomanip>
using namespace std;
int main()
{
cout.setf(ios::showbase);
cout.setf(ios::hex)
cout<<2123<<endl;
system("pause");
return 0;
}


我再DEV C++和Visual Studio 2005试过了都没有效果
...全文
1224 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
taodm 2010-01-07
  • 打赏
  • 举报
回复
呃,请一定使用cout << std::hex
setf可以说不是给外部程序员们用的。
hpxcx 2010-01-07
  • 打赏
  • 举报
回复
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout.setf(ios::showbase);
cout.setf(ios::hex,ios::basefield)
cout < <2123 < <endl;
system( "pause ");
return 0;
}
以下文字引用:
http://msdn.microsoft.com/en-us/library/aa984818(VS.71).aspx

ios::setf(_IFlags) should not be used with a flag value of ios::dec, ios::oct, or ios::hex unless you know that none of the base flags are currently set. The formatted input/output functions and operators assume that only one base is set. Instead, use ios_base. For example, setf( ios_base::oct, ios_base::basefield ) clears all base information and sets the base to octal.
就呆在云上 2008-12-22
  • 打赏
  • 举报
回复
#include <iostream> 
#include <iomanip>
using namespace std;
int main()
{
cout.setf(ios::showbase);
cout.unsetf( ios_base::dec );
cout.setf(ios::hex);
cout <<2123 <<endl;
//system( "pause ");
return 0;
}
yooongmoon 2008-12-22
  • 打赏
  • 举报
回复
很奇怪的是,这种只对了一部分。刚在vs2005上试了一下。cout.setf(f);/*f 为: ios_base::oct, ios_base::hex*/都不会起作用,只好直接用<<hex或<<oct,如:cout<<hex<<"a = "<<a<<endl;。但却可以用cout.unsetf(f)清除设置的格式。想不明白啊!
yooongmoon 2008-12-22
  • 打赏
  • 举报
回复
你这个回复没有给出原因,但是链接很好地解决了这个问题!
谢谢了!
mymtom 2007-07-26
  • 打赏
  • 举报
回复
mymtom@fc6:src/csdn/cpp/ios$ cat setf.cpp
#include<iostream>
#include <iomanip>
using namespace std;
int main()
{
cout.setf(ios::showbase);
cout.setf(ios_base::hex, ios_base::basefield);
cout << 2123 << endl;
(void)getchar();
return 0;
}

mymtom@fc6:src/csdn/cpp/ios$ ./setf
0x84b
原因:
除非知道当前没有设置基标志,否则 ios::setf(_IFlags) 不应和 ios::dec、ios::oct 或 ios::hex 的标志值一起使用。格式化的输入/输出函数和运算符假定只设置了一个基。改用 ios_base。例如,setf( ios_base::oct, ios_base::basefield ) 清除所有基信息并将基设置成八进制。
来自:
http://blog.csdn.net/sssxueren/archive/2004/12/29/233352.aspx

64,642

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧