简体   繁体   中英

convert number with decimal places from char to int in c++

I was playing around with VS 2012 and came across a very tricky problem (for me at least). I have a simple program that does mathematical operations on inputs from the command line. However, if you input arguments with decimal places somewhere in the program it seems to forget the numbers after the decimal place.

double add (char const *inp, char const *inp2) {        //addition function
    double val = std::strtol(inp, NULL, 0);
    double val2 = std::strtol(inp2, NULL, 0);
    return val + val2;
}

and then calling the function :

double result = add(argv[1], argv[2]);
printf("%f \n", result);

and call from command line

test 52.2 44.6

returns 96 instead of 96.8.

You want strtod , not strtol . strtol only parses integers.

strtod only takes two arguments, because floating point numbers are always in base 10 (as far as strtod is concerned, anyway.)

I think you are turning your strings into longs (I'm guessing that's what strtol() is...). I was building a calculator and I had that problem - I wrote a function to handel it:

double string_to_double(string str)
{
    int length = (int)str.length();
    double output = 0; //This holds value of output.  Will be added for each 10's digit
    int decimalPos = length - 1;
    for (int i = 0; i < length; i++)
    {
        if(str.at(i) == '.') // Find if there is a decimal point
        {
            decimalPos = i - 1; //Sets Decimal Position
            str.erase(str.begin()+i);
            length--;
        }
    }



    for (int i = 0; i < length; i++)
    {
        switch (str.at(i))
        {
            case '1':
                output += 1*pow(10, decimalPos - i);
                break;
            case '2':
                output += 2*pow(10, decimalPos - i);
                break;
            case '3':
                output += 3*pow(10, decimalPos - i);
                break;
            case '4':
                output += 4*pow(10, decimalPos - i);
                break;
            case '5':
                output += 5*pow(10, decimalPos - i);
                break;
            case '6':
                output += 6*pow(10, decimalPos - i);
                break;
            case '7':
                output += 7*pow(10, decimalPos - i);
                break;
            case '8':
                output += 8*pow(10, decimalPos - i);
                break;
            case '9':
                output += 9*pow(10, decimalPos - i);
                break;
            case '0':
                break;
        }

    }
    return output;
}

...but there is probably a better way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM