scanf - How to use fscanf to read doubles in C -
i writing program takes in unknown number of doubles, each on own line text file. should placing of these elements read array, isn't working. print loop works, prints zeroes. i've tried lot of things , looked lot before coming here. code.
#include <stdio.h> #include <stdlib.h> int main() { //open file read file *file; file = fopen("data.txt","r"); if (file == null) { printf("file not found."); return -1; } //count number of lines in input file int numlines = 0; //change 1 ??? int ch; { ch = fgetc(file); if (ch == '\n') numlines++; } while (ch != eof); //put of data read array; double input[numlines]; int = 0; while ((fscanf(file, "%lf\n", &input[i])) == 1) i++; //close file fclose(file); //test printing elements of array (i = 0; < numlines; i++) printf("%lf\n", input[i]); return 0; }
op's test of fscanf() result good, except code did not check if many numbers in file.
while ((fscanf(file, "%lf\n", &input[i])) == 1) i++; then code ignored last value of i , instead printed numlines times, if fewer scanned.
for (i = 0; < numlines; i++) printf("%lf\n", input[i]); end code should have been
while (i < numlines && (fscanf(file, "%lf\n", &input[i])) == 1) i++; (j = 0; j < i; j++) printf("%lf\n", input[j]); this have printed 0 lines! file needed reset second pass. @paulr
rewind(file); while (i < numlines && (fscanf(file, "%lf\n", &input[i])) == 1) ... a further problem assuming count of '\n' same count of numbers. can fooled given multiple numbers per line or last line having number yet no '\n'.
a simple work-around make input[] 1 larger , use actual scan success count count of numbers print. more robust code read 1 line @ time fgets() , include additional error checks.
Comments
Post a Comment