使用C中的strlen警告 [英] Warning while using strlen in C
问题描述
我是新的C programming.I正在试图通过每行线和打印长度采取从文件线路输入。
这是我的code -
I am new to C programming.I am trying to take input from a file line by line and print length of each line. This is my code-
#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;
}
这是我的输入文件 -
This is my input file-
172.24.2.1
172.24.2.225
172.17.4.41
172.24.4.42
202.16.112.150
172.24.152.10
这是正确
打印编译期间每个line.But的长度,我得到这样的警告 -
This is correctly
printing the length of each line.But during compilation I get this warning-
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));
所以我的问题是,为什么我会收到这样的警告,虽然我的输出是正确的,我怎么能解决这个问题?
先谢谢了。
So my question is why am I getting this warning although my output is correct and how can I fix this? Thanks in advance.
推荐答案
功能的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 <的对象/ code>。你也应该使用
U
格式符为为size_t
是一个无符号类型。
The function strlen
returns an object of type size_t
(cf. ISO 9899:2011§7.24.6.3). You need to specify that the argument you pass to printf
has type size_t
, as opposed to int
. You can do that by adding a z
length modifier (cf. ISO 9899:2011§7.21.6.1/7) specifying an object of type size_t
. You should also use the u
formatting specifier as size_t
is an unsigned type.
printf("%zu\n",strlen(line));
这篇关于使用C中的strlen警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!