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

本文是小编为大家收集整理的关于程序没有在scanf("%c", &ch)行停止,为什么?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

本文来自:IT宝库(https://www.itbaoku.cn)

该程序不在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);
    }
}

推荐答案

在阅读num时,假设您输入2.实际输入流将为2 \ n(\ n是newline字符). 2进入num,并且存在\ n,该\ n进入ch.为避免这种情况,请添加格式指定符的Whitespace.

scanf(" %c", &ch); 

这将忽略任何Whitespaces,Newlines或Tabs.

其他推荐答案

此原因是以前的scanf留下的newline \n字符,按下 Enter 键,以进行下一个读取scanf>.当语句

scanf("%c", &ch);   

执行,然后读到上一个\n由上一个scanf留下的.
要吃掉这个\n您可以在%c指定器之前使用空间. %c指定器之前的空间能够吞噬任何数量的白色空间字符.

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

本文地址:https://www.itbaoku.cn/post/353046.html

问题描述

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

推荐答案

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

scanf(" %c", &ch); 

This will ignore any whitespaces, newlines or tabs.

其他推荐答案

The reason behind this is the newline \n character left behind by previous scanf, when pressing Enter key, for the next read of scanf. When the statement

scanf("%c", &ch);   

executed then it reads that \n left behind by the previous scanf.
To eat up this \n you can use a space before %c specifier. A space before the %c specifier is able to eat up any number of white-space characters.

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