我在我的程序中使用了 gets()
函数来从用户那里获取字符串。
当我检查带有多个参数的 gets()
时,我感到震惊。
gets()
接受了很多参数,但我不知道 gets()
接受的参数数量,以及这些所有参数的实际用途是什么.
void main()
{
char str[10];
printf("Enter the String...:");
gets(str,5,5,5,5,5);
puts(str);
}
代码没有错误,但它会显示与输入相同的参数。
input String : This is a Tesing.
output String : This is a Tesing.
最佳答案
gets()
只接受一个参数。
可能发生的情况是因为您没有包括<stdio.h>
,编译器不知道它的原型(prototype)是什么,也没有发现编译错误,它正好可以工作。
整个程序的正确形式应该是(即使我还在使用 gets()
):
#include <stdio.h>
int main() {
char str[10];
printf("Enter the String...:");
gets(str,5,5,5,5,5);
puts(str);
}
当我在 GCC 下测试时,它弹出一个错误:
error: too many arguments to function 'gets'
并且不要使用 gets()
,它很危险,已在 C11 中删除。使用 fgets()
相反:
fgets(str, sizeof(str), stdin);
编辑:感谢@abelenky 的回答和@chux 的评论,我证实了我的猜测。
在 C11 6.5.2.2 函数调用第 2 小节(约束):
**If the expression that denotes the called function has a type that includes a prototype, the number of arguments shall agree with the number of parameters. **Each argument shall have a type such that its value may be assigned to an object with the unqualified version of the type of its corresponding parameter.
第 6 小节(语义):
If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type
float
are promoted todouble
. These are called the default argument promotions. If the number of arguments does not equal the number of parameters, the behavior is undefined. ...
所以发生的事情是,没有标题 stdio.h
, 编译器不知道 gets()
的原型(prototype),行为未定义,遵循上面的第 6 小节。
通过 header ,编译器知道原型(prototype),根据上面的第 2 小节,它需要生成诊断消息,因为它是一个约束。
关于c - C语言中的gets()接受参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19619661/