c - fgets 可能会由于其他 scanf 的原因而被忽略

标签 c scanf fgets

程序无法编译fgetsteste1功能。或者至少它不能正常工作,它不会让我输入字符串,程序将在打印“Nome do cliente”后立即结束。

如果我禁用其他 scanf在函数中,它将运行没有任何问题。

如何让 fgets 工作?

#include <stdio.h>
void teste1(){
    char teste[50];
    printf("Nome do cliente\n");
    fgets(teste,50,stdin);
}

void teste2(){
    teste1();
}

void teste3(){

        int opc1,opc2;
        printf("\nSeleccione a área desejada\n1- Clientes\n2- Concessionários\n3- Carros de demonstração\n");
        scanf("%d",&opc1);

        printf("\nSeleccione a área desejada\n1- Inserir\n2- Alterar\n3- Remover\n4- Consultar\n");    
        scanf("%d",&opc2);

    teste2();
}

int main()
{
    teste3();
}

最佳答案

您在最后一次 scanf 输入中按下的 Enter 键将作为换行符保留在输入缓冲区中。 fgets 函数将读取此换行符并认为它已完成。

关于c - fgets 可能会由于其他 scanf 的原因而被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41831398/

相关文章:

c - fgets - 省略了 c 中的最后一行

c - 该程序中的 fgets

python - 将变量从 python 脚本传递到 C 程序(命令行参数)

c - 在 C : leading zeros 中读取文件

c - 我想从 stdin 读取文件并将每一行读入字符串并且仅使用 getchar

c++ - scanf() 的宽度说明符 - 要使用的字符长度在编译时不固定,仅在运行时确定。如何使其可变?

c - 为什么在 C 编程中 scanf ("%d", &number) 结果 'a' 为 29?

c - 之前存储的字符串会被 fget 覆盖

编译器找不到已安装的库头文件

c - 主线程退出时,其他线程是否也退出?