tags:

views:

140

answers:

6

Hello. This is a very simple question, but I can't seem to find something about it in here already. I want to read two integers from a file with C. My code now is this:

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 get the first integer from the file, but the next one is just a random number. My file is like this:

100 54

Thanks in advance

+3  A: 

You are reading the results into s and t but printing only s ?

Martin Beckett
+1  A: 

You never initialize it. You pass pointer to s, which means (here) the first element, as a first parameter. What do you expect to show up in s[1]?

Michael Krelin - hacker
+6  A: 

This line:

fscanf(fp, "%d%d", s, &t);

is putting one of the ints in s[0] and the other in t, but you are printing out s[0] (which is your first int) and s[1], which is uninitialized (and hence "random").

fbrereto
+1  A: 

Your problem is on this line:

fscanf(fp, "%d%d", s, &t);
printf("%d %d\n", s[0], s[1]);

You're reading into s[0] and t, but printing s[0] and s[1]. Either of the following would 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]);
JSBangs
A: 

You need to read into &s[0] and &s[1] or print out s[0] and t.

MSN
+1  A: 

When you are doing the fscanf, you are using one set of variables. But when you do the printf, you are using another.

One way to get it working 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;
}
Brian Gianforcaro