Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

c - scanf getchar function is skipped

A very simple question. Why scanf is skipped in the first while loop. I have tried it by using getchar() and the result is same. getchar is skipped.

If you guys dont understand what I'm talking about you can tried compile it and you guys will understand what i'm asking about.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct rec{
    int num;
    char pref[16];
    float point;
    struct rec* next;
}rec;

void dataInput(float*,char*);
rec* insertNode(rec*);

int main(){

    int i=1;
    rec* entr,*pt = NULL;
    entr = (rec*) malloc(sizeof(rec));
    entr->num = i;
    dataInput(&entr->point,entr->pref);
    entr->next = NULL;
    char key;
    i++;

    while(1){

        printf("Continue ? If YES press 'y',or NO press 'n'
");
        key = getchar();
        if(key == 'n')break;
        else if(key == 'y'){
            if(!pt){
                pt = insertNode(entr);
            }else{
                pt = insertNode(pt);
            }
            dataInput(&pt->point,pt->pref);
            pt->num = i;
            i++;
            continue;
        }else{
            printf("Wrong key! Please Press again! 
");
        }

    }

    pt = entr;
    while(pt){

        printf("num : %d, pref :  %s, point: %.1f
",
                pt->num,
                pt->pref,
                pt->point);
        pt = pt->next;
    }

    getchar();
    getchar();
    return 0;
}

void dataInput(float* point,char* pref){

    printf("Input Point : ");
    scanf("%f",point);

    printf("Input Pref : ");
    scanf("%s",pref);
}

rec* insertNode(rec* current){
    rec* newnode = (rec*)malloc(sizeof(rec));
    current->next = newnode;
    newnode->next = NULL;
    return newnode;
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's because scanf will leave a ' ' (endline) symbol in the input buffer. This symbol will be consumed by getchar at the first iteration of this while(1) loop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...