【问题标题】:The program doesn't stop on scanf("%c", &ch) line, why? [duplicate]程序不会在 scanf("%c", &ch) 行停止,为什么? [复制]
【发布时间】:2021-12-18 20:40:26
【问题描述】:

程序不会在 scanf("%c", &ch) 行上停止。为什么会这样,有人能解释一下吗

#include<stdlib.h>
#include<stdio.h>

struct list {
   char val;
   struct list * next;
};

typedef struct list item;

void main()
{
    char ch;
    int num;

    printf("Enter [1] if you want to use linked list or [2] for realloc\n");  
    scanf("%d", &num);
    if(num == 2)
    {
        scanf("%c", &ch); 
        printf("%c", ch);
    }
}

【问题讨论】:

  • 基本上,虽然scanf 的几乎所有其他格式说明符都会去除前导空格,但%c 是个怪人。你必须非常小心地对待它。

标签: c


【解决方案1】:

假设您在阅读 num 时输入了 2。实际输入流将是 2\n(\n 是换行符)。 2 进入 num,剩下的 \n 进入 ch。为避免这种情况,请在格式说明符中添加一个空格。

scanf(" %c", &ch); 

这将忽略任何空格、换行符或制表符。

【讨论】:

    【解决方案2】:

    这背后的原因是前一个scanf 留下的换行符\n 字符,当按下Enter 键时,用于下一次读取scanf。当声明

    scanf("%c", &ch);   
    

    执行然后读取\n 被前一个scanf 留下。
    要吃掉这个\n,您可以在%c 说明符之前使用一个空格。 %c 说明符之前的空格可以占用任意数量的空白字符。

    scanf(" %c", &ch);   
           ^ a space
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      相关资源
      最近更新 更多