c - writing float to file under specific conditions?

So I'm creating a program called convert.c that takes in data from a csv file and writes the data to a new textfile called data.bin (but with alterations to the original csv file). One field/column of the csv file in particular contains a column of integers (representing the magnitude of each earthquake), which were written to the data.bin file.

The magnitude should be written to the file as a float ONLY if this specific disaster was an earthquake. Otherwise nothing should be written.

The problem is I'm having trouble with the "nothing is written if it wasn't an earthquake" part. The thirdfield = " " line doesn't work because I declared it as a float since it should print as a float, but a blank space would be a character type. And for the print statement, %f doesn't really work if it's a blank space that needs to be printed. I'm not sure what to do to solve this issue. I only need the float to be printed under certain conditions, and print nothing elsewise. 

float thirdfield = 0;

if(strcmp(second, "Earthquake") == 0){

  thirdfield = strtof(third, NULL);

}else{

  thirdfield = " ";

//...

fprintf(ft, "%f \n", thirdfield);

2 Answers

Relevance
  • 1 month ago
    Favorite Answer

    Why so complicated? You said you wanted to write nothing, so what about

    ...

    if (strcmp (second, "Earthquake") == 0) fprintf(ft, "%f \n", strtof(third, NULL));

    If you actually want to print a newline instead of nothing, you'll need an else statement like

    else fprintf(ft, "\n");

    Or reduce it a bit more with

    if(...) fprintf(ft, "%f", strtof(third, NULL));

    fprintf(ft, "\n");

    • Login to reply the answers
  • Tasm
    Lv 6
    1 month ago

    Cast your else statement strtof

    • Login to reply the answers
Still have questions? Get your answers by asking now.