C++ 为什么std::hex和std::oct标志不起作用?
这是我的代码:C++ 为什么std::hex和std::oct标志不起作用?,c++,hex,iostream,flags,C++,Hex,Iostream,Flags,这是我的代码: // This program demonstrates the use of flags. #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string filename; bool tf; double number; cout << "Name a file to create/
// This program demonstrates the use of flags.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string filename; bool tf; double number;
cout << "Name a file to create/overwrite: ";
cin >> filename;
ofstream outfile (filename.c_str());
if(outfile.fail())
{
cout << "Creating/Overwriting the file has failed.\nExiting...\n";
return 1;
}
cout << "Give me a boolean (0/1): "; cin >> tf;
cout << "Give me a large number with decimal points: "; cin >> number;
outfile.setf(ios_base::boolalpha); // Turns on boolalpha flag.
outfile << "Here's a boolean: " << tf << endl;
outfile.unsetf(ios_base::boolalpha); // Unsets boolalpha flag.
outfile << "Here's your number: " << number << endl;
outfile.setf(ios_base::scientific); // Turns on scientific notation flag.
outfile << "Here's your number is scientific notation: " << number << endl;
outfile.setf(ios_base::fixed); // When possible, floating point numbers will not appear in scientific notation.
outfile << "Here's your number in fixed notation: " << number << endl;
outfile.setf(ios_base::hex); // Numbers will appear in hexadecimal format.
outfile << "Here's your number in hexadecimal format: " << number << endl;
outfile.setf(ios_base::oct, ios_base::uppercase); // Numbers will appear in uppercase, octal format.
outfile << "Here's your number in octal format: " << number << endl;
return 0;
}
为什么当我设置“十六进制”和“十月”标志时,它们不起作用
在文本文件中,我期望的不是“十六进制格式:”和“八进制格式:”旁边的“3591.67”
我是否实现了错误的标志?不幸的是,八进制和十六进制打印只适用于整数,而不适用于双精度。看 如果您希望使用setf,它应该是:
outfile.setf(ios_base::hex,ios_base::basefield);
。或者,标准为十六进制的管道,即:
outfile << std::hex;
outfile八进制和十六进制格式仅影响整数的显示方式。如果要查看十六进制的浮点数,可以使用hexfloat
(C++11)或使用cstdio
中的printf
函数和%a
格式化代码
另请参见函数“int main()”中的flags.cpp:flags.cpp:37:16:错误:“hexfloat”不是“std::ios_base”outfile.setf(ios_base::hexfloat)的成员;//数字将以十六进制格式显示^hexfloat是c++11标准的一部分。编译器是否已设置为使用它?对于g++,您需要添加--std=c++11,我想是这样。。。仍然不工作。。。g++flags.cpp-o标志--std=c++11@Evan:这取决于您的编译器版本。他们并没有一次性实现所有的C++11。我将变量“number”更改为“int”类型,但问题仍然存在…请尝试outfile.setf(ios_base::hex,ios_base::basefield)?setf被重载以执行两种不同的操作。setf(x)或的x带有格式标志,而setf(x,y)将格式标志设置为(x&y)。因此,它不起作用的原因可能是因为其他一些格式标志,比如科学记数法,被设置了,但没有被setf“清除”,所以它没有按照预期的方式运行。我猜,因为我不完全确定。
outfile << std::hex;