C - 从文本文件中获取单个Int

时间:2016-06-11 02:52:44

标签: c

我有一个看起来像这样的文本文件:

4
3
Samantha Octavia Ivan Henry
100 90 65 70
99 50 70 88
88 90 98 100

我想要单独阅读前两行并将它们打印出来,但现在它正在给我一个巨大的数字。

inputFile = fopen ("input.txt", "r");

//input
    if( inputFile == NULL)
    {
        printf ("Unable to open file input.txt");
        exit(EXIT_FAILURE);
    }
    else
    {
        printf ("How many students?\n ");
        fscanf (inputFile, "%d", &students);
        printf ("%d", &students);
        printf ("\nHow many assignments?\n ");
        fscanf (inputFile, "%d", &assignments);
        printf ("%d", &assignments);
        printf ("\n");
    }

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

简单错误!

打印& students或&作业的价值不正确。这将打印指向该变量的指针的值。您需要以下代码:

    printf ("How many students?\n ");
    fscanf (inputFile, "%d", &students);
    printf ("%d", students); // not &students
    printf ("\nHow many assignments?\n ");
    fscanf (inputFile, "%d", &assignments);
    printf ("%d", assignments); // not &assignments
    printf ("\n");