Fortran十进制和千位分隔符 [英] Fortran decimal and thousand separator
问题描述
是否可以更改逗号的句点小数点分隔符?
此外,如何使输出数字具有千位分隔符?这可能是逗号,句点,空格...
您可以编写一个C ++函数,该函数将为您在当前语言环境中转换字符串中的数字.
#include< string>#include< iomanip>#include< sstream>class SpaceSeparator:public std :: numpunct< char>{上市:SpaceSeparator(std :: size_t refs):std :: numpunct< char>(refs){}受保护的:char do_thousands_sep()const {return'';}char do_decimal_point()const {return',';}std :: string do_grouping()const {返回"\ 03";}};extern"C" {void convert(char * str,double f,int len){std :: string s;std :: stringstream输出;SpaceSeparator facet(1);//1-完成后不要删除std :: locale prev = out.imbue(std :: locale(std :: locale(),&facet));出<<std :: setprecision(15)<<F;s = out.str();std :: copy(s.begin(),s.end(),str);我为(i = s.size(); i< len; i ++){str [i] ='';}}}
从Fortran拨打电话:
使用iso_c_binding界面子例程convert(str,f,l)bind(C,name ="convert")进口字符(c_char):: str(*)实(c_double),值:: f整数(c_int),值:: l结束子程序终端接口字符(len = 100,kind = c_char):: ch调用convert(ch,123456.123_c_double,len(ch,kind = c_int))打印*,ch结尾
在我的机器上,它会打印 123 456,123
:
>gfortran locale.cc locale.f90 -lstdc ++>./a.out123 456,123
免责声明:我不是C ++程序员,他的解决方案可能很慢.也许Fortran中的蛮力方法更好.
我以这个答案为基础: https://stackoverflow.com/a/2648663/721644 >
Is there a way to change the period decimal separator for a comma?.
Also, how can I make the output numbers have a thousand separator?. This could be a comma, a period, a space ...
You can write a C++ function which will convert the number in a string in you current locale for you.
#include <string>
#include <iomanip>
#include <sstream>
class SpaceSeparator: public std::numpunct<char>
{
public:
SpaceSeparator(std::size_t refs): std::numpunct<char>(refs) {}
protected:
char do_thousands_sep() const { return ' '; }
char do_decimal_point() const { return ','; }
std::string do_grouping() const { return "\03"; }
};
extern "C" {
void convert(char* str, double f, int len) {
std::string s;
std::stringstream out;
SpaceSeparator facet(1); //1 - don't delete when done
std::locale prev = out.imbue(std::locale(std::locale(), &facet));
out << std::setprecision(15) << f;
s = out.str();
std::copy(s.begin(), s.end(), str);
int i;
for (i=s.size();i<len;i++){
str[i] = ' ';
}
}
}
call from Fortran:
use iso_c_binding
interface
subroutine convert(str, f, l) bind(C,name="convert")
import
character(c_char) :: str(*)
real(c_double), value :: f
integer(c_int), value :: l
end subroutine
end interface
character(len=100,kind=c_char) :: ch
call convert(ch, 123456.123_c_double, len(ch, kind=c_int))
print *,ch
end
On my machine it prints 123 456,123
:
> gfortran locale.cc locale.f90 -lstdc++
> ./a.out
123 456,123
Disclaimer: I am not a C++ programmer and he solution can be slow. Maybe the brute force approach in Fortran is better.
I used this answer as a base: https://stackoverflow.com/a/2648663/721644
这篇关于Fortran十进制和千位分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!