2012-11-20 154 views
1

一个非常简单的问题。为什么scanf在第一个while循环中被跳过。 我已经通过使用getchar()来试用它,结果是一样的。 getchar被跳过。scanf 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; 
} 

回答

6

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

+0

是的!有用!! if(key =='\ n'){key = getchar(); } 后我添加它。谢谢 – edisonthk

3

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

您可以使用在scanf函数使用前导空格解决这个问题:

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

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

+0

Omg您提出的第二个选项对我来说是* ONLY WORKING OPTION *。我尝试了近15个类似问题中提到的所有东西。在%c之前添加一个空格不起作用,在%c无效后添加\ n,使用fflush(stdin)不起作用,gets,getchar和scanf都有同样的问题...呃...你知道这是为什么吗? –

+0

可能是由于任何后续的scanf/fgets调用等。不看代码就看不出来。但我建议阅读:http://c-faq.com/stdio/scanfprobs.html并避免scanf()。 –