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.
3 Answers
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);
2 Comments
&next_number for the 2nd argument in the 3rd statement? (perhaps useful as a test eg in a looping construct.)"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;
}
strtok()