Char as a decimal separator in C

你。 提交于 2019-12-13 20:43:27

问题


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!


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/13701284/char-as-a-decimal-separator-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!