【问题标题】:scanf getchar function is skippedscanf getchar 函数被跳过
【发布时间】:2012-11-20 12:57:23
【问题描述】:

一个非常简单的问题。为什么 scanf 在第一个 while 循环中被跳过。 我已经通过使用 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;
}

【问题讨论】:

    标签: c


    【解决方案1】:

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

    【讨论】:

    • 是的!有用!! if(key == '\n'){ key = getchar(); } 在我添加它之后。谢谢
    【解决方案2】:

    getchar() 在输入缓冲区中留下一个换行符,由后续的 scanf() 读取。

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

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

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

    【讨论】:

    • 天哪,您建议的第二个选项对我来说是唯一可行的选项。我尝试了近 15 个类似问题中提到的所有内容。在 %c 前加空格无效,在 %c 后加 \n 无效,使用 fflush(stdin) 无效,gets、getchar 和 scanf 都有同样的问题...呃...你知道这是为什么吗?
    • 可能是由于任何后续的 scanf/fgets 调用等。不看代码就无法判断。但我建议阅读以下内容:c-faq.com/stdio/scanfprobs.html 并完全避免 scanf()。
    【解决方案3】:

    只需在scanf() 之后使用另一个getchar() 即可使用换行符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 2019-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-07
      相关资源
      最近更新 更多