c ++如何在文件中打印带逗号(而不是点)的双十进制数

c++ How to print in a file a double decimal number with comma(instead of dot)

我需要打印一个包含数字的 csv 文件。 打印文件时,我有带点的数字,但我需要带逗号的数字。

举个例子。 如果我使用语言环境方法在终端中打印此数字,我将获得一个带逗号的数字,但在文件中我有相同的数字但带有点。我不懂为什么。 我该怎么办?

#include <iostream>
#include <locale>
#include <string>     // std::string, std::to_string
#include <fstream>
using namespace std;
int main()
{
    double x = 2.87;
    std::setlocale(LC_NUMERIC, "de_DE");
    std::cout.imbue(std::locale(""));
    std::cout << x << std::endl;
    ofstream outputfile ("out.csv");
    if (outputfile.is_open())
        {
            outputfile  <<to_string(x)<<"\n\n";
        }
    return 0;
}

提前致谢。

您的问题是 std::to_string() 使用 C 语言环境库。 "de_DE" 似乎不是您机器上的有效语言环境(或 Coliru 就此而言),导致使用默认的 C 语言环境并使用 .。解决方案是使用"de_DE.UTF-8"。顺便说一句,对 std::locale 使用 "" 并不总是会产生逗号;相反,它将取决于为您的机器设置的语言环境。

区域设置为 system-specific。您可能只是打错了字;尝试 "de-DE",这可能会起作用(至少它在我的 Windows 上起作用)。


但是,如果您的程序本身不是 German-centric,那么滥用德语语言环境只是为了获得特定小数点字符的副作用是糟糕的编程风格,我认为。

这是使用 std::numpunct::do_decimal_point 的替代解决方案:

#include <string>
#include <fstream>
#include <locale>

struct Comma final : std::numpunct<char>
{
    char do_decimal_point() const override { return ','; }
};

int main()
{
    std::ofstream os("out.csv");
    os.imbue(std::locale(std::locale::classic(), new Comma));
    double d = 2.87;
    os << d << '\n'; // prints 2,87 into the file
}

这段代码特别指出它只需要标准的 C++ 格式,只用 ',' 替换小数点字符。它没有提及特定国家或语言,或 system-dependent 属性。