使用fscanf扫描字符串 [英] Scanning strings with fscanf in C

查看:167
本文介绍了使用fscanf扫描字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮我解决一些问题。

该文件包含:

  AAAA 111 BBB 
CCC 2222 DDDD
EEEEE 33 FF

代码是:

  int main(){
FILE * finput;

int i,b;
char a [10];
char c [10];

finput = fopen(input.txt,r); (i = 0; i <3; i ++){
fscanf(finput,%s%i%s \ n,& a,& b,和C);
printf(%s%i%s \ n,a,b,c);
}

fclose(finput);
返回0;
}

代码确实有效。但是,会出现以下错误:

 格式«%s»需要类型为«char *»的参数参数3具有类型«char(*)[10] 
格式«%s»期望类型«char *»的参数,但参数5具有类型«char(*)[10]

类型是否错误?问题是什么?

解决方案

数组名称衰减到指向它们第一个元素的指针,所以为了传递数组的地址到 fscanf(),您应该直接传递数组:

  fscanf(finput,%s%i%s \\\
,a,& b,c);

这相当于:

<$ p $ fscanf(finput,%s%i%s \ n,& a [0],& b,& c [0]);

但显然使用 a 而不是& a [0] 更方便。

你写这个的方式, > value (这就是为什么它可以工作),但是这个值有一个不同的 type :它不再是指向 char 的指针,而是一个指向 char s的数组的指针。这不是 fscanf()所期望的,所以编译器会警告它。

有关解释,请参阅: https://stackoverflow.com/a/2528328/856199


Please, help me to fix some problems.

The file contains:

AAAA 111 BBB
CCC 2222 DDDD
EEEEE 33 FF

The code is:

int main() {
    FILE * finput;

    int i, b;
    char a[10];
    char c[10];

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

    for (i = 0; i < 3; i++) {
        fscanf(finput, "%s %i %s\n", &a, &b, &c);
        printf("%s %i %s\n", a, b, c);
    }

    fclose(finput);
    return 0;
}

The code does work. However, the following errors occur:

format «%s» expects argument of type «char *», but argument 3 has type «char (*)[10]
format «%s» expects argument of type «char *», but argument 5 has type «char (*)[10]

Are the types wrong? What's the problem?

解决方案

Array names decay to a pointer to their first element, so in order to pass the addresses of the arrays to fscanf(), you should simply pass the arrays directly:

fscanf(finput, "%s %i %s\n", a, &b, c);

This is equivalent to:

fscanf(finput, "%s %i %s\n", &a[0], &b, &c[0]);

But obviously using a instead of &a[0] is more convenient.

The way you wrote it, you're passing the same value (that's why it works), but that value has a different type: it's not a pointer to a char anymore, but a pointer to an array of chars. That's not what fscanf() is expecting, so the compiler warns about it.

For an explanation, see: https://stackoverflow.com/a/2528328/856199

这篇关于使用fscanf扫描字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆