开发者

Formatting issue with fgets in a function

I am asking for input from a functions using fgets. I keep getting a annoying bug, in which the program skips right over the input开发者_如何学Go and goes to input of the second variable. I have no idea what seems to be the problem. The code in question is below. It reads from getchar(), and if it is 'n' it goes the 2nd function.

#include <stdio.h>

void enter(){
    char name[20];

int Age;
float Highbp;
float Lowbp;

    printf("name: ");
    fgets(name, 20, stdin);

    printf("age: ");
    scanf("%d", &Age);

    printf("high bp: ");
    scanf("%f", &Highbp);

    printf("low bp: ");
scanf("%f", &Lowbp);


    return ;

    }
    void option(){

        char choice = getchar();

        if(choice == 'n'){

        enter();
        }
    }
int main(int argc, char **argv)
{

option();
}

output produced (not the whole output):

>n
>name: age: 

This works now

printf("name: ");
while(getchar()!='\n');

fgets(name, 20, stdin);


I didn't run your code so I can only guess. This sounds familiar:

the program skips right over the input and goes to input of the second variable.

It is related to these questions:

  • The compiler seems to be skipping the call to gets!
  • Scanf problems
  • Explanations + possible solutions

The input stream after the first scanf call still contains a \n, so the gets call reads it right away, without pausing for you to enter anything more. The problem is that the gets call satisfies its need for input in an unexpected way

So it's probably some leftover \n somewhere.

EDIT

I re-read your code and I believe your problem is:

char choice = getchar(); /* leaves a \n in the buffer */


That's because the stdin buffer has a newline buffered in it. To remove it, use :

fflush(stdin);

So your code is now like this:

#include <stdio.h>

void enter(){
char name[20];

int Age;
float Highbp;
float Lowbp;

printf("name: ");
fflush(stdin);
fgets(name, 20, stdin);

printf("age: ");
scanf("%d", &Age);

printf("high bp: ");
scanf("%f", &Highbp);

printf("low bp: ");
scanf("%f", &Lowbp);


return ;

}
void option(){

    char choice = getchar();

    if(choice == 'n'){

    enter();
    }
}
int main(int argc, char **argv)
{

option();
}

Edited

Since, everybody here says that it is discouraged to use fflush(stdin); (Although it had worked for me everytime. :) ) Here is another solution. Instead of fflush(stdin) use:

while(getchar()!='\n');

That will empty the buffer for the newline that may skip next fgets call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜