简体   繁体   中英

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

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

您正在将结果读入 s 和 t 但只打印 s ?

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

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

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;
}

您需要读入&s[0]&s[1]打印出s[0]t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM