How to use atof in C

Asked

Viewed 2,307 times

0

Could you help me use the atof function? My code is giving "access Violation" in the line I am using atof, already tried to change the type of the "given" array to both int and float

int main() {
char pilha[10];
int i;
int dado[10];
int topo = 0;

printf("Informe a expressao\n");
gets(pilha);
fflush(stdin);

for (i = 0; i < strlen(pilha); i++)
{
    if (isdigit(pilha[i]))
    {
        dado[topo] = atof(pilha[i]);
        topo++;
    }
}

1 answer

1


The atof function is used to convert a string to a double. Strings in C end with ' 0' and when you do atof(stack[i]) the program does not find ' 0', which would indicate that it is a string, and generates this error, see in the function signature: double atof(const char *str); Use the Strtok() function to separate your stack variable into several strings according to a separation pattern, the function’s signature is: char *Strtok(char *str, const char *delim), where char *str is the string you want to separate and const char *delim is the string that has the string that will be used to make that separation. Example of use:

#include <string.h>
#include <stdio.h>
int main(){
   char str[80] = "Isto eh - um - teste";
   char s[2] = "-";
   char *token;
   /* pega o primeiro token */
   token = strtok(str, s);
   /* caminha através de outros tokens */
   while( token != NULL ){
      printf( " %s\n", token );
      token = strtok(NULL, s);
   }
   return(0);
}
  • Wow, true! I ended up forgetting that in C to be string has to end with ' 0'. Thank you very much, Matheus!!!

Browser other questions tagged

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