Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How would I go about scanning float values in a text file with whitespace characters using I/O Redirection?

I’m pretty new to programming in C and I have a school assignment that requires me to use I/O Redirection and strictly use scanf to read the data from a text file.

I’m mostly checking whether or not the code I’ve written makes sense and is a plausible method because I can’t check whether it works currently (may or may not have dropped my laptop).

Here’s what I’ve written so far.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <stdio.h>
#include <math.h>

int main(void){
    int readingsLen = 5040;
    float readings[readingsLen];
    float* readingsPtr = (float*)readings;

    while (scanf("%.2f", readingsPtr) != EOF){
        readingsPtr++;
    }
}

Additionally, here’s what the text file looks like. Added the \n to show where the line ends.

 22.12  22.43  25.34  21.55 \n

>Solution :

You can use the pointer:

#include <stdio.h>
#include <math.h>

#define LEN 5040

int main(void){
    float readings[LEN];
    for(float *readingsPtr = readings; readingsPtr < readings + LEN; readingsPtr++) {
        if(scanf("%f", readingsPtr) != 1)
            break;
        printf("read %.2f\n", *readingsPtr);
    }
}

and here is resulting output:

read 22.12
read 22.43
read 25.34
read 21.55

Here is a version that uses an index instead:

#include <stdio.h>
#define LEN 5040

int main(void){
    float readings[LEN];
    for(int i = 0; i < LEN; i++) {
        if(scanf("%f", &readings[i]) != 1)
            break;
        printf("read %.2f\n", readings[i]);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading