-3

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);
Khawker
  • 11
  • 1

1 Answers1

2

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.

user2736738
  • 30,591
  • 5
  • 42
  • 56
  • I'd prefer to use `{ strcpy(help, (char[2]){c}); }` :-) – alk Jan 27 '18 at 13:04
  • Note the curly braces around the statement to limit the life time of the compound literal. – alk Jan 27 '18 at 13:06
  • @alk.: The thing is my earlier solution also is taking the benefit of the curly braces..yes I get it. If I dont put it...then it;s life time will be depend on that of the nearest enclosing block. – user2736738 Jan 27 '18 at 13:08
  • "*They provide extended error checking.*" only those functions provide **complete** error checking. – alk Jan 27 '18 at 19:42
  • @alk.: Yes...these don't provide at all. – user2736738 Jan 27 '18 at 19:43