Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
837 views
in Technique[技术] by (71.8m points)

Char as a decimal separator in C

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] = '';       

    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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...