0

リンクされたリストを学習しています。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 プロセッサー。
4

2 に答える 2

1
 why does scanf behave so differently with character data types?

これscanfは、 がそのように動作するように作られているためです。実際には非常に複雑な機能であり、必要になるまで回避する必要があります。ただし、主な理由は、フォーマット文字列のスペースは、 %c を除いて、次の入力項目の前の空白をスキップすることを意味するという事実にあります。

したがって、scanf("%d%d", &n, &m)は と同じように動作しscanf("%d %d", &n, &m)ます。の場合%c、フォーマット文字列にスペース文字を追加すると違いが生じます。たとえば%c、フォーマット文字列で の前にスペースがある場合、scanf()空白以外の最初の文字までスキップします。つまり、このコマンドは、scanf("%c", &ch)入力で検出された最初の文字をscanf(" %c",&ch)読み取り、最初に検出された空白以外の文字を読み取ります。

空白も文字であることに注意してください

C11 標準によると ( 7.21.6.2 fscanf 関数、セクション #8 )

指定に[c、またはn指定子が含まれていない限り、入力空白文字 (関数 isspace で指定) はスキップされます。

于 2013-08-28T23:37:13.190 に答える