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
+2
source to share
6 answers
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]);
+2
source to share
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;
}
+1
source to share