c - 用户输入的问题

标签 c

<分区>

我现在在大学学习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 个字符)

关于c - 用户输入的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19331980/

相关文章:

c - OSX Leopard 上来自 NetBeans 7.1 的 GDB 不会在库项目的断点处停止

c - 如何打印当前时间和日期

c - 使用互斥体和信号量

c++ - 使用数组时的常见陷阱 : Trusting type-unsafe linking

c - getenv - Mac OS X 和 Linux 上的环境变量

c - 如何在c中递归地将字符串反转为空字符串

c - 使用 wordwrap 2 的最佳消息框大小

c - getpeername 后出现段错误

c - 查找数组中元素的最大总和的算法,使得不超过 k 个元素相邻

不使用 memcpy() 复制字节