2017-02-19 60 views
2

我需要打印一个带有数字的cvs文件。 打印文件时,我有带点的数字,但我需要用逗号。C++如何在文件中用逗号(而不是点)打印一个双精度的十进制数字

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

#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

灌输物流对象,而不是cout。 –

+0

@尼尔[似乎没有帮助](http://coliru.stacked-crooked.com/a/2947e8488c8fb6a2)。 –

+0

请注意,您需要为'std :: setlocale'包含''。它可能在没有头文件的情况下工作,但不能保证(例如,如果没有Visual C++,它不会编译)。 –

回答

0

区域设置是系统特定的。你可能只是犯了一个错字;尝试"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++与仅','取代了小数点的字符格式。它没有提及具体的国家或语言,或与系统相关的属性。

2

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

+0

[有趣!](http://coliru.stacked-crooked.com/a/1fe5711da15e03f1) –

+0

更确切地说,'std :: to_string'被定义为以'sprintf' ,'sprintf'使用C语言环境库。 –

相关问题