0

Can we use strtod for convert string ("1.234 34.345 245.356") to double? because when I use strtod it only convert the first number.

1
  • Check out strtok() Commented Sep 2, 2021 at 13:19

3 Answers 3

6

That's how any standard conversion function is supposed to work.

However, if you read the strtod documentation you will see that is has an str_end argument, which is a pointer that can be initialized to the end of the parsed number in the string. You can use this pointer to parse the next number in the string.

For example something like this:

char string[] = "1.234 34.345 245.356";
char *next_number = string;

double number1 = strtod(next_number, &next_number);
double number2 = strtod(next_number, &next_number);
double number3 = strtod(next_number, NULL);
Sign up to request clarification or add additional context in comments.

2 Comments

Couldn't you also just use &next_number for the 2nd argument in the 3rd statement? (perhaps useful as a test eg in a looping construct.)
@ryyker Of course. I'm just showing how to work with a specific string, it can be modified to work with generic strings in a loop (but then null-pointer checks must be added).
0

"Can we use strtod for convert string ("1.234 34.345 245.356") to double?"

Yes, strtod(...) is designed for just that purpose.
The following illustrates reading any number of values from stdin, and parsing into array using strtod(...).
(Usege of strtok(), in helper function provides count of inputs to use in creating dynamically sized array to store parsed numbers.)

int main()
{
    char buffer[1024] = {0};
    double *array = NULL;
    int count = 0, i = -1;
    
    printf("%s", "Enter numbers separated with spaces, then <return>\n");
    fgets(buffer, sizeof buffer, stdin);
    buffer[strcspn(buffer, "\n")] = 0;
    char *next_num = buffer;
    char *dup = StrDup(buffer);
    if(dup)
    {
        count = count_numbers(dup);
        array = calloc(count, sizeof(*array));
        if(array)
        {
            for(i=0;i<count;i++)
            {
                array[i] = strtod(next_num, &next_num);
            }
            //use array
            //...
            free(array);
        }
        free(dup);
    }
    return 0;
}

int count_numbers(const char *nums)
{
    char *tok = NULL;
    char *delim = " \t\n,";
    int count = 0;
    tok = strtok(nums, delim);
    while(tok)
    {
        count++;
        tok = strtok(NULL, delim);
    }
    return count;
}

Comments

0

Other answers have discussed strtod, and a comment mentions strtok. Another possibility is sscanf:

char *str = "1.234 34.345 245.356";
double a, b, c;
int n = sscanf(str, "%lf %lf %lf", &a, &b, &c);
printf("got %d values\n", n);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.