Char as a decimal separator in C

2019-08-27 03:50发布

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.

Here is the 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; 



} 

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?

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.

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.

Thank you!

3条回答
Ridiculous、
2楼-- · 2019-08-27 04:28

You can simply extend your code:

if ( 
            (str[i] == '-' && minus) 
            || (str[i] >= '0' && str[i] <= '9') 
            || (str[i] == 'e' || str[i] == 'E') 
            ) 

to

char separator = ','; //or whatever you want
int have_separator = 0;

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

Please note that this is only some try to show the idea - not the real working code (but it could work anyway). You can use similar concept.

查看更多
该账号已被封号
3楼-- · 2019-08-27 04:29

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.

查看更多
混吃等死
4楼-- · 2019-08-27 04:46

Well I know that using String.Split does this sor of thing but I think you should write your own function for it stop when it found the first one.

here is the msdn website for more help on that

MSDN Split

查看更多
登录 后发表回答