字符在C小数点分隔 [英] Char as a decimal separator in C

查看:114
本文介绍了字符在C小数点分隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了从字符串双提取功能。喜欢用点作为小数点分隔asfas123123afaf到123123或afafas12312.23131asfa为12312.23131。

I've written a function that extracts double from a string. Like asfas123123afaf to 123123 or afafas12312.23131asfa to 12312.23131 using the point as a decimal separator.

下面是code:

double get_double(const char *str, char sep)
{


    char str_dbl[80]; 
    size_t i,j; 
    char minus; 
    double dbl; 

    for (minus = 1, i = j = 0; i < strlen(str); ++i) 
    { 

        if ( 
            (str[i] == '-' && minus) 
            || (str[i] >= '0' && str[i] <= '9') 
            || (str[i] == 'e' || str[i] == 'E') 
            ) 
        { 
            str_dbl[j++] = str[i]; 
            minus = 0; 
        } 
    } 
    str_dbl[j] = '\0';       

    dbl = strtod (str_dbl,NULL); 

    return dbl; 



} 

但现在我想设置从ASCII码字符一个用户定义的逗号分隔符(字符SEP)(不属于对^ 10文字E或E)。我怎么能实现呢?

But now I want to set a user defined comma separator (char sep) from the ASCII-chars (without E or e that are literals for ^10). How could I implement it?

让我sepcify这一点:我们说的分隔符是','因此字符串是123123asfsaf,ADSD,as.1231它应该返回123123,1231为双。它承认第一','(左起),而忽略其他。

Let me sepcify this: We say the separator is ',' so the string is 123123asfsaf,adsd,as.1231 it should return 123123,1231 as a double. It recognizes the first ',' (from left) and ignore all other.

这是真的很难让我找到这个问题的解决方案。我曾经想过的setlocale但我似乎并没有最好的解决办法。

It is really hard for me to find a solution for this problem. I have thought about setlocale but I it doesn't seem the best solution.

感谢您!

推荐答案

您可以只更换任何操作前的的strtod

You can just replace any , with . before doing the strtod.

如果您由于某种原因不想修改源字符串,将它复制到一个新字符串第一。

If you for some reason don't want to modify the source string, copy it to a new string first.

这篇关于字符在C小数点分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆