scanf getchar函数被跳过 [英] scanf getchar function is skipped

查看:54
本文介绍了scanf getchar函数被跳过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个非常简单的问题.为什么在第一个while循环中跳过scanf.我已经尝试过使用getchar(),结果是一样的.getchar被跳过.

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'\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! \n");
        }

    }

    pt = entr;
    while(pt){

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

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

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

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

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

rec* insertNode(rec* current){
    rec* newnode = (rec*)malloc(sizeof(rec));
    current->next = newnode;
    newnode->next = NULL;
    return newnode;
}

推荐答案

这是因为 scanf 将在输入缓冲区中保留'\ n'(结束行)符号.此符号将在 while(1)循环的第一次迭代中由 getchar 消耗.

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

这篇关于scanf getchar函数被跳过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆