c - scanf AFTER fgets 破坏了 fgets 语句

标签 c scanf fgets

我看过各种关于在 fgets 之前使用 scanf 可能会导致问题的帖子。但是,对我来说,为什么在 AFTER 之后添加它会导致第一个语句中断,这是没有意义的。

这就是我所拥有的:

  unsigned char key;
  unsigned char message[100];

  printf(" Please input a message \n  ");
  fgets(message, MAX_BUF, stdin); 
  printf("Your message is:  %s \n", message);


  // Read user input for message
  printf(" Please input a numeric key\n  ");
  scanf("%d", &key);

  printf("Your message is:  %s \n", message);
  printf("strlen(message) = %d \n", strlen(message));

这是一次“试运行”:

  Please input a message
   hello
   Your message is: hello

  Please input a numeric key
   123

  Your message is: 
  strlen(message) = 0

像这样,无论输入如何,消息变量最终都会为空。但是,如果我用 scanf 注释掉该行,则一切正常(除了我无法分配 key )。

救命!

最佳答案

scanf()%d 格式说明符 promise 下一个参数是足够大以容纳 的内存缓冲区的地址int(通常为 4 或 8 个字节),但您的 key 只是一个 1 字节的 unsigned char,因此 scanf()将在末尾写入 3 个(或者可能 7 个)字节,践踏占用该内存的任何内容 - 在本例中,很可能是消息。它到底写入的内容取决于系统的字节序,但对于小字节序系统(例如 x86)上的小输入(<= 255),其第二个字节(将被写入 message 的第一个字节)将为 0,这实际上以零长度以 null 终止消息

关于c - scanf AFTER fgets 破坏了 fgets 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26172078/

相关文章:

c - 你如何在 C 中的 Linux 上进行非阻塞控制台 I/O?

c - 代码片段段错误的起源

c - 将csv文件读入c中的二维数组

c - 当您将 12ab 之类的内容输入到 scanf ("%d",&argu 时会发生什么?

c - 尝试在 C 中使图像在像素级别上变大时获取访问冲突写入位置 0xCDCDCDCD

c - 阵列扫描两次?

c - scanf 并指向 int* 段错误

c - C 中的 fgets() 函数

c - 使用 fgets 从文件读取 Seg Failure 错误

c - fgets() 在 C 中从 stdin 接收输入的段错误