Function that reads a double of a string and returns the rest of the string in C

Asked

Viewed 151 times

1

Is there any function of the type? Which reads and stores or returns a double of a string and returns or pointers the rest of the string or do I have to do my own function? If there is no one have ideas on how to do this function optimally?

1 answer

1


There is the function:

double strtod (const char* str, char** endptr);

She converts a number double from the string passed as the first parameter, and plays in the second parameter a pointer to the rest of the string. Example:

#include <stdio.h> 
#include <stdlib.h>  

int main ()
{
  char texto[] = "1.21 gigawatts";
  char* resto;
  double num;
  num = strtod (texto, &resto);
  printf ("Num: %f\n", num);
  printf ("Resto: %s\n", resto);
  return 0;
}

Exit:

Num: 1.210000
Resto:  gigawatts
  • Just to make one last question, using the strod() function, has some form of the pointer received by the rest being the same as the "main" string or the best method to do it is by a strcpy()?

  • It will be the "same" yes. Internally it should only increment the pointer of the first parameter, and write it in the second at the end.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.