John Taylor
John Taylor

Reputation: 163

Simple code with convertation the string into the double doesn't work

I have the code which must get the double number from the file:

#include <stdio.h>   
#include <string.h> 

FILE *fr;           

int main(void)
{
    int n;
    double elapsed_seconds;
    char line[80];
    fr = fopen ("time1.log", "rt");    
    sscanf (line, "%3.6f", &elapsed_seconds);   
    printf ("%3.6f\n", elapsed_seconds);
    fclose(fr);  
} 

Now, time1.log contains only number 0.145213. But the program prints 0. Where is the problem?

Upvotes: 0

Views: 42

Answers (3)

user3629249
user3629249

Reputation: 16540

the posted code is missing a critical line:

Not only does the code need to open the file, it also needs to read the file into the line variable.

Either insert, just after the call to fopen()

fgets( line, sizeof(line), fr );

or (less desirable) replace the call to sscanf() with

fscanf(fr, "%lf", &elapsed_seconds);

Note: if your keep the call to sscanf() then the format string should be: "%lf", the same as for the call to fscanf()

using the call to fscanf() would allow the elimination of the line[] array.

The variable n is never used, so should be eliminated

Upvotes: 2

nalzok
nalzok

Reputation: 16097

It should be

#include <stdio.h>   
#include <string.h> 

FILE *fr;           

int main(void)
{
    int n;
    double elapsed_seconds;
    char line[80];
    fr = fopen ("time1.log", "rt");   
    fgets(line, 80, fr);                           // <--- Note this line
    sscanf (line, " %lf", &elapsed_seconds);   
    printf ("%3.6f\n", elapsed_seconds);
    fclose(fr);  
} 

This is because you have to read the data from the file to the string before sscanfing that string.

Upvotes: 2

Wayne Booth
Wayne Booth

Reputation: 422

Before calling sscanf to parse the data, you need to read the data from the file - call fgets(line,80,fr).

Upvotes: 0

Related Questions