为了账号安全,请及时绑定邮箱和手机立即绑定

scanf getchar函数被跳过

scanf getchar函数被跳过

C
湖上湖 2019-12-06 14:54:44
一个非常简单的问题。为什么在第一个while循环中跳过scanf。我已经尝试过使用getchar(),结果是一样的。getchar被跳过。如果你们不明白我在说什么,您可以尝试编译它,你们会明白我在问什么。#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;}
查看完整描述

3 回答

?
慕标5832272

TA贡献1966条经验 获得超4个赞

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


查看完整回答
反对 回复 2019-12-06
?
BIG阳

TA贡献1859条经验 获得超6个赞

getchar() 在输入缓冲区中留下换行符,随后的scanf()会读取该换行符。


您可以通过在scanf中使用前导空格来解决此问题:


scanf(" %c ...", &c,..);

告诉scanf忽略所有空白字符。或者getchar()在第一个getchar()之后使用另一个权利来使用换行符。


查看完整回答
反对 回复 2019-12-06
  • 3 回答
  • 0 关注
  • 671 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信