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

时间:2017-02-19 17:32:33

标签: c++ printing locale fstream cout

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

这是一个例子。 如果我使用locale方法在终端中打印此号码,我会用逗号获取一个数字,但在文件中我有相同的数字但是带有点。我不懂为什么。 我该怎么办?

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

提前致谢。

2 个答案:

答案 0 :(得分:2)

您的问题是std::to_string()使用C语言环境库。看来"de_DE"不是您计算机上的有效语言环境(或者Coliru),导致使用.默认的C语言环境。解决方案是使用"de_DE.UTF-8"。另外,对""使用std::locale并不总是会产生逗号;相反,它将取决于为您的机器设置的区域设置。

答案 1 :(得分:1)

语言环境是特定于系统的。你可能只是写了一个错字;尝试"de-DE",这可能会起作用(至少它在我的Windows上)。

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

以下是使用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 ++格式,只有小数点字符替换为','。它没有引用特定国家或语言或系统相关属性。