【问题标题】:c++ How to print in a file a double decimal number with comma(instead of dot)c ++如何用逗号(而不是点)在文件中打印双十进制数
【发布时间】:2017-02-19 17:32:33
【问题描述】:

我需要打印一个带有数字的 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;
}

提前致谢。

【问题讨论】:

  • 灌输 ofstream 对象,而不是 cout。
  • 请注意,std::setlocale 需要包含 &lt;clocale&gt;。它可以在没有标头的情况下工作,但不能保证(例如,在 Visual C++ 中没有标头就无法编译)。
  • 文件是csv,不是cvs
  • 我更正了,谢谢

标签: c++ printing locale fstream cout


【解决方案1】:

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

【讨论】:

  • 更准确地说,std::to_string 被定义为根据 sprintf 工作,sprintf 使用 C 语言环境库。
【解决方案2】:

语言环境是系统特定的。您可能只是打错了字;试试"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++ 格式,只需将小数点字符替换为 ','。它没有提及特定国家或语言,或系统相关属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 2013-05-02
    • 2018-03-17
    • 2016-08-30
    相关资源
    最近更新 更多