/edited/
I’m new here.
I have a text file that reads:
6
<cr>
R 0
R 1
R 4
R 36
R 0
R 4
This is what I have. I want to read each line into an array so that I can convert that array into an integer so I can print only the numbers of whichever line I want later.
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
FILE *fr; /*declares file pointer*/
int i, j, num[32];
char array[32][32], input_file[32], line[32];
printf("Enter file: ");
fflush(stdin);
scanf("%s", input_file);
fr = fopen(input_file, "r");
for(i=0;i<32;i++)
for(j=0;j<32;j++){
array[i][j] = \'0';
}
for(i=0;i<32;i++){
line[i] = '\0';
}
if(fr != NULL){
while(fgets(line, sizeof(line), fr) != NULL){
strcpy(array[i],line);
num[i] = atoi(array[i]);
i++;
printf("%d\n", num[i]);
}
}fclose(fr);
else{
perror(input_file);
}
}
I’m not getting any errors but it isn’t printing the right thing; this is what it prints:
-370086
-370086
-370086
-370086
-370086
-370086
-370086
-370086
Can anyone explain to me what is going wrong?
I think I’d handle this a bit differently. Though you haven’t stated it explicitly, I’m going to assume that the first number is telling us how many more lines of letters/numbers we’re going to read (not including the blank line). So, we want to read that, then read the rest of the lines, ignoring any leading non-digits, paying attention only to the numbers.
If that’s correct, we can simplify the code somewhat: