How to convert decimal numbers stored as characters in a string to doubles?

86 views Asked by At

New to programming, I'm looping through a postfix string and trying to retrieve the numbers individually, I only need one at a time.

Initially I wrote this for integers and just did "- '0'", however, I now need to try and make it compatible for decimal numbers.

An example of my integer conversion is below, how could I adapt this?

int i;
char postfix[] = "4 3 +";

for (i=0; i<strlen(postfix); i++) {
    if (isalnum(postfix[i])) {
        int value=(postfix[i]-'0');
        printf("%d\n", value);
    }
}

4
3

e.g. how to evaluate when

char postfix[] = "1.2 3.4 +"

storing the value as a double

2

There are 2 answers

0
Krishna Kanth Yenumula On
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{

    int i;
    double res;
    char *ptr1;
    char *ptr2;
    char postfix[] = "4.5 3.4 4.5 7.6 8.9 3.6 +";

    ptr1 = postfix;
    res = strtod(ptr1, &ptr2);
    
    
    while (res!= 0.0f )  // strtod() return 0.0 if double value is not found.
    {
        printf("Value in decimal is %lf\n",res);
        ptr1 = ptr2;
        res = strtod(ptr1, &ptr2);
    }
    return 0;
}

The output is :

Value in decimal is 4.500000
Value in decimal is 3.400000
Value in decimal is 4.500000
Value in decimal is 7.600000
Value in decimal is 8.900000
Value in decimal is 3.600000

Please see this link to know about strtod() function :https://linux.die.net/man/3/strtod

0
chux - Reinstate Monica On

Use strtod() to parse the string for a valid double.

current == endptr implies conversion failed.

char postfix[] = "4 3 +";
char *current = postfix;
char *endptr;

double v1 = strtod(current, &endptr);
if (current == endptr) TBD_code_handle_failure();
else current = endptr; 

double v2 = strtod(current, &endptr);
if (current == endptr) TBD_code_handle_failure();
else current = endptr; 

while (isspace((unsigned char) *current)) {  // skip white-space
  current++;
}

if (strchr("+-*/", *current) == NULL) {
  TBD_code_handle_failure(); // unexpected operator
}

printf("%g %g %c\n", v1, v2, *current);

Or ....

double v1, v2;
char oper;
if (sscanf(postfix, "%lf %lf %c", &v1, &v2, &oper) == 3) {
  ; // Success!
}