我现在在大学学习C。我想从用户那里获取输入,然后将其打印在屏幕上。我尝试了 scanf 和 fgets,但它们都崩溃了。请帮助我需要学习如何获取输入然后打印它。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char name[256];
printf("Write something:\n");
gets(name);
printf("You wrote: %s", name) ;
return 0;
}
gets
是危险的且已弃用:
Since the user cannot specify the length of the buffer passed to
gets(), use of this function is discouraged. The length of the string
read is unlimited. It is possible to overflow this buffer in such a
way as to cause applications to fail, or possible system security
violations.
使用fgets相反:
fgets(name, 256, stdin);
或
fgets(name, sizeof(name), stdin);
它不会崩溃(即使你输入超过 255 个字符)