为什么std :: hex和std :: oct标志不起作用?

问题描述 投票:2回答:2

这是我的代码:

// 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;
}

我运行此程序时...

Linux Terminal

test.txt]的内容>:

Here's a boolean: false
Here's your number: 3491.67
Here's your number is scientific notation: 3.491670e+03
Here's your number in fixed notation: 3491.67
Here's your number in hexadecimal format: 3491.67
Here's your number in octal format: 3491.67

为什么设置“十六进制”和“八进制”标志时它们不起作用?

[在文本文件中,我期望“十六进制形式:”和“八进制格式:”旁边的“ 3591.67”以外的内容。

我是否将标志实现错误?

这是我的代码://此程序演示了标志的使用。 #include #include #include 使用命名空间std; int main(){字符串文件名;布尔...

c++ hex iostream flags
2个回答
3
投票

不幸的是,八进制和十六进制打印仅适用于整数,而不适用于双精度。参见http://stdcxx.apache.org/doc/stdlibug/28-3.html

如果您想使用setf,应该是:

outfile.setf(ios_base::hex,ios_base::basefield);

2
投票

八进制和十六进制格式仅影响整数的显示方式。如果要以十六进制形式查看浮点数,则可以使用hexfloat(C ++ 11)或将printf中的cstdio函数与%a格式代码一起使用。

另请参阅Dump hex float in C++

© www.soinside.com 2019 - 2024. All rights reserved.