【问题标题】:Warning while using strlen in C在 C 中使用 strlen 时出现警告
【发布时间】:2015-03-20 15:28:17
【问题描述】:

我是 C 编程新手。我正在尝试逐行从文件中获取输入并打印每行的长度。 这是我的代码-

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

int main()
 {

    char name[100];
    printf("Enter file name\n");
    scanf("%s",name);



    FILE * input;
    input=fopen(name,"r");

    char line[100];
    fscanf(input,"%s",line);

    while(!feof(input))
    {

        printf("%d\n",strlen(line));
        fscanf(input,"%s",line);
    }


    return 0;
 }

这是我的输入文件-

172.24.2.1
172.24.2.225
172.17.4.41
172.24.4.42
202.16.112.150
172.24.152.10

这是correctly 打印每行的长度。但是在编译过程中我收到了这个警告-

In function ‘main’:
main.c:24:4: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘size_t’ [-Wformat=]
    printf("%d\n",strlen(line));

所以我的问题是,尽管我的输出是正确的,但为什么我会收到此警告,我该如何解决这个问题? 提前致谢。

【问题讨论】:

标签: c


【解决方案1】:

函数strlen 返回一个size_t 类型的对象(参见ISO 9899:2011§7.24.6.3)。您需要指定传递给printf 的参数的类型为size_t,而不是int。您可以通过添加 z 长度修饰符(参见 ISO 9899:2011§7.21.6.1/7)指定 size_t 类型的对象来做到这一点。您还应该使用u 格式说明符,因为size_t 是无符号类型。

printf("%zu\n",strlen(line));

【讨论】:

  • size_t 是无符号类型,因此格式说明符应为%zu%zd 用于签名类型,如 ssize_t
猜你喜欢
  • 1970-01-01
  • 2022-01-07
  • 2021-12-09
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 2011-07-22
  • 1970-01-01
相关资源
最近更新 更多