gpt4 book ai didi

c - 函数中 fgets 的格式化问题

转载 作者:太空宇宙 更新时间:2023-11-04 00:41:30 24 4
gpt4 key购买 nike

我正在使用 fgets 请求来自函数的输入。我不断收到一个烦人的错误,其中程序直接跳过输入并转到第二个变量的输入。我不知道问题出在哪里。有问题的代码如下。它从 getchar() 中读取,如果它是 'n',它就进入第二个函数。

#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();
}

产生的输出(不是全部输出):

>n
>name: age:

现在可以了

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

fgets(name, 20, stdin);

最佳答案

我没有运行你的代码,所以我只能猜测。这听起来很熟悉:

the program skips right over the inputand goes to input of the secondvariable.

它与这些问题有关:

The input stream after the first scanfcall still contains a \n, so thegets call reads it right away, withoutpausing for you to enter anythingmore. The problem is that the getscall satisfies its need for input inan unexpected way

所以它可能是一些剩余的 \n 某处。

编辑

我重新阅读了您的代码,我认为您的问题是:

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

关于c - 函数中 fgets 的格式化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6555877/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com