utdiscant
utdiscant

Reputation: 11542

Reading ints from file with C

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

Upvotes: 3

Views: 2480

Answers (6)

Brian Gianforcaro
Brian Gianforcaro

Reputation: 27210

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]);
    fclose(fp);
  }

  return 0;
}

Upvotes: 1

MSN
MSN

Reputation: 54634

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

Upvotes: 0

JSBձոգչ
JSBձոգչ

Reputation: 41388

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]);

Upvotes: 2

fbrereto
fbrereto

Reputation: 35935

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").

Upvotes: 6

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143269

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]?

Upvotes: 1

Martin Beckett
Martin Beckett

Reputation: 96167

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

Upvotes: 3

Related Questions