程序不等待用户在 while(1) 循环中接受用户的输入

Program is not waiting for user to take input from user inside while(1) loop

我正在使用数组实现 Stack 数据结构。要在堆栈上执行 Push 或 Pop 或从程序退出等操作,我以整数形式从用户那里获取输入(比如 1 表示 Push)。

为了连续获取用户的输入,我 运行 一个 while(1) 循环,在一个循环内要求用户给出一个整数作为所需操作的输入。

问题:在执行过程中,程序没有等待用户输入就进入死循环。我已尝试使用 fflush 清除标准输入,但仍然无法正常工作。

请查看下面的代码并给出评论和帮助。

谢谢。

//Main function


int main(){


STACK marks, roll_number;      //marks and roll_number are two stacks of type STACK

//Initialize both Stacks with required size
initStack(&marks, 10);
initStack(&roll_number, 10);

int choice, marks_data;

//Menu for user to choose from available operations
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Exit\n");

//Taking user input for operations
while(1){

    printf("Enter choice of Operation:\n");

    //Clearing standard input. Although not a best practice but implementing to
    //take user input
    fflush(stdin);
    // program is not stopping here and taking invalid choice
    //hence executing 'default statement' of switch case
    scanf("%d", &choice);


    switch(choice){

    case 1: printf("Enter Marks");
            scanf(" %d", &marks_data);
            push(&marks, marks_data);
            break;

    case 2: marks_data = pop(&marks);
            printf("Deleted Data : %d\n", marks_data);
            break;

    case 3: exit(0);

    default: printf("Invalid Choice of Operation !!\n");
    }

    //using to clear \n character from user and taking valid input
    printf("Press Enter Key to continue...");
    while(getchar() != '\n')
        getchar();
}

    return 0;
}

当您使用 scanf 时,您必须打开 "account's hat" 并考虑从输入缓冲区读取的所有字符,或输入缓冲区中未读的所有字符。在数字和字符输入之间混合输入或在代码中混合输入函数时尤其如此。

在您的情况下,您为 choicemarks 调用 scanf ("%d", ...),但随后尝试使用以下方法控制循环执行:

printf("Press Enter Key to continue...");
while(getchar() != '\n')
    getchar();

作为一名优秀的 scanf 会计师,您知道使用 '%d' 格式说明符 阅读会读取从 stdin 到第一个的数字non-digit 字符并终止读取,留下 stdin 中的 non-digit 字符未读。 (假设在 choicemark 之后没有输入杂散字符),这将是在您之前输入后按 Enter 生成的 '\n' 字符。

当您测试 while(getchar() != '\n') 时,读取的第一个字符可能是 '\n' 字符,导致您的循环测试 TRUE 并跳过 getchar() 在循环内调用。

最简单的解决方案就是在当前的下面添加一个额外的 getchar()

下一个 fflush(stdin) 在除 windows 之外的几乎所有系统上都是 未定义行为 。在 Linux 上,定义了 fflush(stdin),但仅适用于 可搜索的 流——仅适用于 stdin 如果文件已被 重定向到您在stdin上的程序,例如

./yourexe < somefile.txt

否则fflush(stdin)未定义。所以你必须问问自己——除了 windows 之外的所有东西都是 non-portable 除非 stdin 作为重定向的结果是可搜索的 —— "Is is really good practice to use anywhere?" 和 "How do I force the user to redirect a file to stdin?"(你不能)。所以最好一路避开。

检查一下,如果您还有其他问题,请告诉我。