Reading ASCII numbers using “D” instead of “E” for scientific notation using C

后端 未结 3 1445
执笔经年
执笔经年 2020-12-21 21:33

I have a list of numbers which looks like this: 1.234D+1 or 1.234D-02. I want to read the file using C. The function atof will merely

相关标签:
3条回答
  • 2020-12-21 22:05

    Here this function is to replace "D" into "E" in the scientific notation with "D".

    std::string dToE(string cppstr)
    {
        str1.replace(cppstr.find("D"),1,"E");
        return cppstr;
    }
    

    If the C string for scientific notation is defined by: char * cstr = "1.2D+03"; or usually obtained by strtok method, which returns C string, then use atof(dToE(string(cstr)).c_str()) to get the scientific notation with "E".

    Since atof only accept C style string, you should use c_str() string method to convert C++ string into C string.

    0 讨论(0)
  • 2020-12-21 22:07

    You can take advantage of strtod and strtok:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(void) {
        char in[] = "1.234D+1 ABCD 1.234D-02 5\n";
        char *cursor;
        char *endp;
        for ( cursor = strtok(in, " "); cursor; cursor = strtok(NULL, " ")) {
            double d = strtod(cursor, &endp);
            if ( *endp == 'D' ) {
                *endp = 'e';
                d = strtod(cursor, &endp);
            }
            if ( endp != cursor ) {
                printf("%e\n", d);
            }
        }
        return 0;
    }
    

    Output:

    E:\> cnv
    1.234000e+001
    1.234000e-002
    5.000000e+000
    0 讨论(0)
  • 2020-12-21 22:14

    replace D with E, by looping along string. then atof.

    0 讨论(0)
提交回复
热议问题