程序不会在 scanf("%c", &ch) 行停止,为什么? [英] The program doesn't stop on scanf("%c", &ch) line, why?

查看:23
本文介绍了程序不会在 scanf("%c", &ch) 行停止,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序不会在 scanf("%c", &ch) 行停止.为什么会这样有人可以向我解释一下

the program doesnt stop on scanf("%c", &ch) line. why does it happens sombody can please explain this to me

#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
");  
    scanf("%d", &num);
    if(num == 2)
    {
        scanf("%c", &ch); 
        printf("%c", ch);
    }
}

推荐答案

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

Let's say you input 2 when you're reading for num. The actual input stream will be 2 ( is the newline character). 2 goes into the num, and there remains , which goes into ch. To avoid this, add a whitespace in format specifier.

scanf(" %c", &ch); 

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

This will ignore any whitespaces, newlines or tabs.

这篇关于程序不会在 scanf("%c", &amp;ch) 行停止,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆