This question already has an answer here:
这个问题在这里已有答案:
- C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf [duplicate] 7 answers
C:多个scanf,当我输入一个scanf的值时,它会跳过第二个scanf [复制] 7个答案
I am new to C and I'm trying to learn linked list but for some reason I can't give more than one value. The program ends after giving one value. Here is my code:
我是C的新手,我正在尝试学习链表,但出于某种原因,我不能给出多个值。程序在给出一个值后结束。这是我的代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct node_type {
int data;
struct node_type *next;
} node;
int main()
{
typedef node *list;
list head, temp;
char ch;
int n;
head = NULL;
printf("enter Data?(y/n)\n");
scanf("%c", &ch);
while ( ch == 'y' || ch == 'Y')
{
printf("\nenter data:");
scanf("%d", &n);
temp = (list)malloc(sizeof(node));
temp->data = n;
temp->next = head;
head = temp;
printf("enter more data?(y/n)\n");
scanf("%c", &ch);
}
temp = head;
while (temp != NULL)
{
printf("%d", temp->data);
temp = temp->next;
}
return 0;
}
1 个解决方案
#1
Change this : scanf("%c", &ch);
to this scanf(" %c", &ch);
改变这个:scanf(“%c”,&ch);到此scanf(“%c”,&ch);
The reason that your code did not take any input was because the scanf consumed the newline from the buffer. The blank space before %c
causes scanf() to skip white space and newline from the buffer before reading the character intended.
您的代码没有接受任何输入的原因是因为scanf从缓冲区消耗了换行符。 %c之前的空白区域会导致scanf()在读取预期字符之前跳过缓冲区中的空格和换行符。
#1
Change this : scanf("%c", &ch);
to this scanf(" %c", &ch);
改变这个:scanf(“%c”,&ch);到此scanf(“%c”,&ch);
The reason that your code did not take any input was because the scanf consumed the newline from the buffer. The blank space before %c
causes scanf() to skip white space and newline from the buffer before reading the character intended.
您的代码没有接受任何输入的原因是因为scanf从缓冲区消耗了换行符。 %c之前的空白区域会导致scanf()在读取预期字符之前跳过缓冲区中的空格和换行符。