简体   繁体   English

用 C 从文件中读取整数

[英]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:我想用 C 从一个文件中读取两个整数。我现在的代码是这样的:

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[0] ,另一个放入t ,但您正在打印s[0] (这是您的第一个整数)和s[1] ,它未初始化(因此是“随机”)。

您正在将结果读入 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].您正在阅读 s[0] 和 t,但打印的是 s[0] 和 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.您将指针传递给s ,这意味着(此处)第一个元素作为第一个参数。 What do you expect to show up in s[1] ?你期望在s[1]什么?

When you are doing the fscanf, you are using one set of variables.当您执行 fscanf 时,您使用的是一组变量。 But when you do the printf, you are using another.但是当您执行 printf 时,您正在使用另一个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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