Search code examples
cchartype-conversionintgetc

How to get float from file using getc() in C?


I have a file with ";" as a separator, i want to get some characters and save them as float, I've come up with something like this:

int c;
char help[10];
float x;
while(getc(c)!=';'){
strcpy(help, c);
}
float = atof(help);

Solution

  • Correct usage of getc. It is int getc(FILE *stream). So you need to provide the stream from which it reads.

    while(getc(c)!=';'){ <-- wrong
       strcpy(help, c);  <-- wrong
       ...
    

    is wrong. The second parameter to strcpy should be a nul termnated char array.

    char cs[]={c,0}
    strcpy(help,cs);
    

    or even betteralk suggested

    {strcpy(help, (char[2]){c});}
    

    About the input part you can do this though:

     while((c=getc(stdin))!=';'){ 
       ...
    

    Instead of using atof it is much better to use strtof or strtod functions. They provide error checking unlike these ato* functions.