Search code examples
cpow

How to convert a char* to a number function with a comma (decimal point)?


I wrote change() to help me convert a string to a double.

For example: if the string is "5.5", I want the number to be 5.5. If the string is "0.0", I want the number to be 0. Another example: "50" to 50.

Now the problem is when I use the change() with pow() that is in the library math.h, everything works perfectly fine and I tested it with a lot of inputs and all worked perfect.

Example to a test :

change("5.0") gives me 5
change("1.5") gives me 1.5

Since I can't use the library math I wrote power(), but when I test change(), now I don't get an output. I think it is stuck in an infinite loop.

Any help why this thing is happening?

double change(char* Point) {
    int count = 0;
    double res = 0;
    while (*Point == '0') {
        Point++;
    }
    while (*Point != '.' && *Point) {
        count++;
        Point++;
    }

    int num1 = 0;
    for (int i = 0; i < count; i++) {
        Point--;
        num1 = (*Point - '0') * (power(10, i));
    }

    int i = -1;
    while (*Point != '.' && *Point) {
        Point++;
    }
    double num2 = 0;
    if (!*Point) {
        return res = (double) num1 + num2;

    }
    Point++;
    while (*Point) {
        num2 = (double) (*Point - '0') * (double) (power(10, i));
        i--;
        Point++;
    }
    res = (double) num1 + num2;

    return res;
}

I also wrote the function power:

int power(int base,int exp)
{
    int result=1;
    if(exp == 0){
        return 1;
    }
    while (exp != 0)
    {
        result=result*base;
        exp--;
    }
    return result;
}

Solution

  • Because you call the function power(10,i) in the change function, while i have a negative value. You can fix this by adding an if statement in your power function

    if (exp < 0) {
        exp = 0 - exp;
        return(1/power(base,exp));
    }
    

    Edit : you also have to change the power function to return double instead of int