gpt4 book ai didi

c - 程序没有在 scanf ("%c", &ch) 行停止,为什么?

转载 作者:行者123 更新时间:2023-11-30 16:21:08 25 4
gpt4 key购买 nike

程序不会在 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 是换行符)。 2 进入 num,剩下\n,进入 ch。为了避免这种情况,请在格式说明符中添加空格。

scanf(" %c", &ch); 

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

关于c - 程序没有在 scanf ("%c", &ch) 行停止,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54988342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com