リンクされたリストを学習しています。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);
}
}
コメントを参照してください
エラーチェックはこちら
私が言及しているステートメントを知るためのコードで。
ここで、フォーマット指定子の前にスペース、つまり scanf ステートメントの %c の前にスペースを追加すると、コードが正常に実行されます。.
scanf(" %c",&ch);
scanf の代わりに getchar を使用すると、同じ問題に直面します
ch=getchar();
scanf ステートメントでフォーマット指定子の前にスペースを使用せずにコードを実行するか、getchar() ステートメントを使用すると、プログラムは入力を要求しません。ch には何も格納しません。その背後にある理由を誰か説明してもらえますか?文字データ型で scanf の動作が大きく異なるのはなぜですか?
追加情報:
- GCC の使用
- Linux カーネル 3.6.11-4
- OS フェドラ 16 (64 ビット)
- インテル i5 プロセッサー。