Reading ints from a file with C
This is a very simple question, but I cannot find something about it here. I want to read two integers from a file with C. Now my code is:
int main() {
FILE *fp;
int s[80];
int t;
if((fp=fopen("numbers", "r")) == NULL) {
printf("Cannot open file.\n");
} else {
fscanf(fp, "%d%d", s, &t);
printf("%d %d\n", s[0], s[1]);
}
return 0;
}
I am getting the first integer from the file, but the next one is just a random number. My file looks like this:
100 54
Thank you in advance
This line:
fscanf(fp, "%d%d", s, &t);
puts one of an int in s[0]
and the other in t
, but you print s[0]
(which is your first int) and s[1]
that is uninitialized (and therefore "random").
Are you reading the results in s and t, but only printing s?
Your problem is this line:
fscanf(fp, "%d%d", s, &t);
printf("%d %d\n", s[0], s[1]);
You read s [0] and t, but you print s [0] and s [1]. Any of the following will work as a replacement:
fscanf(fp, "%d%d", s, &t);
printf("%d %d\n", s[0], t);
Or:
fscanf(fp, "%d%d", &s[0], &s[1]);
printf("%d %d\n", s[0], s[1]);
You never initialize it. You are passing a pointer to s
, which means (here) the first element, as the first parameter. What do you expect to see in s[1]
?
When you execute fscanf, you are using one set of variables. But when you do printf you are using a different one.
One way to make it work correctly:
#include "stdio.h"
int main()
{
FILE *fp;
int s[80];
if((fp=fopen("numbers", "r")) == NULL) {
printf("Cannot open file.\n");
} else {
fscanf(fp, "%d%d", &s[0], &s[1]);
printf("%d %d\n", s[0], s[1]);
}
return 0;
}
You need to read in &s[0]
and &s[1]
or print s[0]
and t
.