gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:32:15 25 4
gpt4 key购买 nike

这是我的代码:

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

为什么当我设置“hex”和“oct”标志时,它们不起作用?

在文本文件中,我期望“十六进制形式:”和“八进制格式:”旁边不是“3591.67”。

我是否错误地实现了标志?

最佳答案

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

如果你想使用 setf,它应该是:

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

.或者,管道输入 std:hex,即:

outfile << std::hex;

.

关于c++ - 为什么 std::hex 和 std::oct 标志不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32029902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com