简体   繁体   中英

Reading lines of a txt file as floats in C

I have a text file with text that goes like this:

p 1.002 2.705 3.601
p 4.005 9.001 1.044
...

I want to get the float values and assign them to variable. So far I've got

FILE *fileStream = fopen("file.txt, "r");
char fileText[100];
float x;
while (fgets(fileText, sizeof fileText, fileStream))
    {
        if (fileText[0] == 'p')
        {
            x = fileText[2];
            printf("%f",x);
        }
    }
    fclose(fileStream);

But it's printing out some float that isn't on the line. I am new to C, so I'm not sure how to go about getting the floats. Would really appreciate any help.

If you want to read floating-point numbers from a txt file, maybe you should use fscanf function to read every value you want from a file.

In my opinion, you should use following instruction to read a floating-point number by your text file you provided:

fscanf(fileStream, "p %f", &x);

By the function above, p is read and ignored but the first floating-point number is read and put in the variable x and you can print it by printf("%f", x); .

You can also read more about it in Tutorialspoint .

Second, You're going to get a compile-time error by this instruction you entered in your code:

x = fileText[2];

That's because you can't initialize a couple of characters to a floating-point number. It's meaningless. To convert a string into a floating-point number, you should use this function to convert a string into a floating-point number:

x = atof(fileText);

by the function above, if your program was able, it's converted fileText into a floating-point number and put it in x variable.

You should include stdlib.h to use atof() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM