-2

So i have this string:

1, 3.8  , 4.0 , 2 e

And this function that split my string with comma and tab and print my numbers:

void readuserinput(char *ch)
{
    ch = strtok(ch, ", \t");
    char *ptr;
    double ret;
    while (ch)
    {
        ret = strtod(ch, &ptr);
        double d = atof(ch);
        printf("%f", d);
        ch = strtok(NULL, ", \t");
    }
}

So in case i have non number for example e, any chance to check it and in case this is not number print error ?

Is C Language have double parse or something like that ?

user2214609
  • 4,713
  • 9
  • 34
  • 41

1 Answers1

1

You can use strtod to convert form string to double. As per the documentation, it ignores whitespace characters and, if the string is not a valid floating point number, returns 0. You should be able to easily check if the first non-whitespace character of the string is zero or not, to be able to detect if there has been an error or not.

However, note that if the string is something like 1.23xer43, you will get 1.23 (i.e. it converts the first characters).

Paul92
  • 8,827
  • 1
  • 23
  • 37