<分区>
我正在学习链表,当我使用 scanf 输入字符时,代码编译正常,但在运行时它不要求输入并跳过 scanf 语句。
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *ptr;
};
struct node* allocate();
struct node* create();
void display(struct node*);
int main()
{
struct node *new;
new=create();
display(new);
return 0;
}
struct node* allocate()
{
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
return temp;
}
struct node* create()
{
struct node *start,*next;
char ch;
start=next=allocate();
printf("Enter data:\n");
scanf("%d",&start->data);
perror("store data");
start->ptr=NULL;
R1: printf("Do you want to enter more data? y or n:: ");
scanf("%c", &ch); //Check for error here
if(ch=='y'||ch=='Y')
{
while(ch=='y'||ch=='Y')
{
next->ptr=allocate();
next=next->ptr;
printf("Enter data:\n");
scanf("%d",&next->data);
next->ptr=NULL;
printf("Do you want to enter more data? y or n:: ");
scanf(" %c",&ch);
}
}
if(ch=='n'||ch=='N')
{
return start;
}
else
{
printf("Please enter correct option.\n");
goto R1;
}
}
void display(struct node* temp)
{
printf("%d\n",temp->data);
while(temp->ptr!=NULL)
{
temp=temp->ptr;
printf("%d\n",temp->data);
}
}
请看评论
Check for error here
在代码中知道我所指的语句。
现在,如果我在格式说明符之前添加一个空格,即在 scanf 语句中的 %c 之前添加一个空格,那么我的代码可以正常运行。 .
scanf(" %c",&ch);
当我使用 getchar 而不是 scanf 时,我遇到了同样的问题
ch=getchar();
当我在 scanf 语句中的格式说明符前没有使用空格或使用 getchar() 语句运行我的代码时,我的程序不要求输入。它在 ch 中不存储任何内容。 谁能解释一下背后的原因?为什么 scanf 对字符数据类型的行为如此不同?
附加信息:
- 使用海湾合作委员会
- Linux 内核 3.6.11-4
- 操作系统 Fedora 16(64 位)
- 英特尔 i5 处理器。