【问题标题】:warning: format ‘%d’ expects argument of type ‘int *’, but argument 5 has type ‘int’ [-Wformat=] [closed]警告:格式“%d”需要“int *”类型的参数,但参数 5 的类型为“int”[-Wformat=] [关闭]
【发布时间】:2017-01-18 11:36:16
【问题描述】:

我不知道怎么了。我是正确的,但我有这样的问题。 这是我第一个用 C 语言连接文件的程序,我不知道我做错了什么。

2.c: In function ‘main’:
2.c:15:11: warning: format ‘%d’ expects argument of type ‘int *’, but argument 5 has type ‘int’ [-Wformat=]
 fscanf(fp,"%s %s %d\n", a,b,c);
           ^

我的程序

#include <stdio.h>
#include <string.h>

int main()
{
    FILE *fp;
    FILE *fb;
    char z;
    char a[20], b[20];
    int c;
    fp=fopen("data.txt","r");
    fb=fopen("bigmoney.txt","a");
    while (z!=EOF)
    {
        z=fgetc(fp);
        fscanf(fp,"%s %s %d\n", a,b,c);
        if (c > 2000)
            fprintf(fb,"%s %s %d\n", a,b,c);
    }
}

文件数据.txt

Jan Nowak 2000
Irena Pierwsza 3000
Irena Druga    2500
Krzysztof Mrugala 3500
Tadeusz Pat 2000
Emiliusz Jeden 1200
Adam Arma 6000
Kornel Robo 5000
Jan Kowalski 15000
agf dahf 524
sdgdagf adgdagf 345345
adgadgf dfdfgh 1168510135
arek kowalski 3300

【问题讨论】:

  • fscanf(... %d ...) 期待一个指针,更改为fscanf(fp,"%s %s %d\n", a,b,&amp;c);,(注意运算符&amp; 的地址),并且您在while 的第一次迭代中使用未初始化的z循环。
  • 错误信息能清晰多少? %d 需要一个int*,您正在传递int
  • 天哪,我只是瞎了眼,我把&放错了地方,谢谢!

标签: c++ c linux file


【解决方案1】:

函数fscanf(实际上是所有scanf-variants)期望,对于每个格式说明符,一个内存地址可以存储读入的值。所以传递给scanf 的参数总是必须是指向值的指针,而不是值。

它与变量ab 一起工作而不是c 的原因是ab 用作指向20 个连续字符的内存块的指针,而c 持有一个整数值(不是指针)。

要克服这个问题,请编写fscanf(fp,"%s %s %d\n", a,b,&amp;c);,这样您就可以提供存储c 的值而不是c 本身的值的内存。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2015-02-27
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 2012-10-04
    相关资源
    最近更新 更多