#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100 // Maximum size of the arrays
int main() {
FILE *file;
int array1[MAX_SIZE], array2[MAX_SIZE];
int i = 0, j = 0;
// Open the file for reading
file = fopen("numbers.txt", "r");
if (file == NULL) {
printf("Error opening file\n");
return 1;
}
// Read the first line of numbers into array1
while (fscanf(file, "%d", &array1[i]) == 1) {
i++;
if (fgetc(file) == '\n') break; // Stop reading when a newline is encountered
}
// Read the second line of numbers into array2
while (fscanf(file, "%d", &array2[j]) == 1) {
j++;
if (fgetc(file) == '\n') break; // Stop reading when a newline is encountered
}
// Print the arrays to verify
printf("Array 1: ");
for (int k = 0; k < i; k++) {
printf("%d ", array1[k]);
}
printf("\n");
printf("Array 2: ");
for (int k = 0; k < j; k++) {
printf("%d ", array2[k]);
}
printf("\n");
// Close the file
fclose(file);
return 0;
}
The above program is not reading second line of numbers from the file. Can you please tell me what is wrong with this program?
Following is the content from the file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
\nmight find that whitespace instead and not detect the end of the line properly.scanffunctions aren't very line-oriented, and are useful for strictly formatted input. You know the max size of each line, so you can usefgetsand then process the line withsscanfor withstrtok.