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
CodePudding user response:
You can use the pointer:
#include <stdio.h>
#define LEN 5040
int main(void){
float readings[LEN];
for(float *readingsPtr = readings; readingsPtr < readings LEN; readingsPtr ) {
switch(scanf("%f", readingsPtr)) {
case EOF:
return 0;
case 0:
printf("failed to read float\n");
return 1;
default:
break;
}
printf("read %.2f\n", *readingsPtr);
}
}
and here is resulting output:
read 22.12
read 22.43
read 25.34
read 21.55
I find this version, that uses an index instead of a pointer, easier to read:
#include <stdio.h>
#define LEN 5040
int main(void){
float readings[LEN];
for(size_t i = 0; i < LEN; i ) {
switch(scanf("%f", readings i)) {
case EOF:
return 0;
case 0:
printf("failed to read float\n");
return 1;
default:
break;
}
printf("read %.2f\n", readings[i]);
}
}