【问题标题】:How would I go about scanning float values in a text file with whitespace characters using I/O Redirection?How would I go about scanning float values in a text file with whitespace characters using I/O Redirection?
【发布时间】:2022-11-20 12:55:39
【问题描述】:

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.

#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

【问题讨论】:

  • To read from files, use fscanf().

标签: c io-redirection


【解决方案1】:

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++) {
        int r = scanf("%f", readingsPtr);
        if(r != 1)
            break;
        printf("read %.2f
", *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++) {
        int r = scanf("%f", &readings[i]);
        if(r != 1)
            break;
        printf("read %.2f
", readings[i]);
    }
}

【讨论】:

  • and strictly use scanf to read the data from a text file— the OP wants the data to be read from a text file and not stdin.
  • @RohanBari That is not my understanding of the question, i.e. "use I/O Redirection and strictly use scanf"
猜你喜欢
  • 2022-12-01
  • 2021-11-18
  • 2022-12-01
  • 2022-12-27
  • 2022-12-01
  • 2022-12-28
  • 2022-12-27
  • 2022-11-20
  • 2022-12-27
相关资源
最近更新 更多