【问题标题】:Repeated printing of message after multiple input with fgetc(stdin)使用 fgetc(stdin) 多次输入后重复打印消息
【发布时间】:2020-07-03 11:21:29
【问题描述】:

我正在编写一个具有 2 个功能的程序。当他打开程序时,要求用户通过输入 1 或 2 作为输入来选择一个。如果用户输入错误,他将被要求再次输入它的选择。

#include <stdio.h>

char c;

int main() {
    printf("What do you wish to do ?\nEnter 1 to convert raw PCM to WAV \nEnter 2 to convert WAV to raw PCM \nChoice : ");
    c = fgetc(stdin);
    while(c != '1' && c != '2') {
        printf("You specified an incorrect input\nEnter 1 to convert raw PCM to WAV\nEnter 2 to convert WAV to raw PCM\nChoice : ");
        c = fgetc(stdin);
    return 0;
}

我通过输入 78 作为输入来测试这种“输入错误”的情况,但这里是控制台输出:

What do you wish to do ?
Enter 1 to convert WAV to raw PCM
Enter 2 to convert raw PCM to WAV
Choice : 78
You specified an incorrect input
Enter 1 to convert raw PCM to WAV
Enter 2 to convert WAV to raw PCM
Choice : You specified an incorrect input
Enter 1 to convert raw PCM to WAV
Enter 2 to convert WAV to raw PCM
Choice : You specified an incorrect input
Enter 1 to convert raw PCM to WAV
Enter 2 to convert WAV to raw PCM
Choice :

在要求进一步输入之前,它会连续三次显示“输入错误”消息。 这种重复的原因可能是什么?
注意:如果我使用 getchar() 而不是 fgetc(stdin),也会发生同样的事情。

【问题讨论】:

  • 两个问题:您按下的Enter 键将作为换行符添加到输入缓冲区,您无需处理;第二个是fgetc 返回一个int,这对于EOF 检查你是否丢失很重要。

标签: c input stdin fgetc


【解决方案1】:

输入 78&lt;Enter&gt; 作为三个单独的字符 '7'、'8' 和 '\n' 添加到输入中。这就是您三次收到无效输入消息的原因。

我的建议是停止使用字符,而是将整行读取为单个字符串,然后尝试将其解析为整数。也许像

// Input validation loop
for (;;)
{
    // Print prompt
    printf("What do you wish to do ?\nEnter 1 to convert raw PCM to WAV \nEnter 2 to convert WAV to raw PCM \nChoice : ");

    // Read the whole next line as input
    char input[256];
    if (fgets(input, sizeof input, stdin) == NULL)
    {
        // TODO: Input error, handle it accordingly
        exit(EXIT_FAILURE);
    }

    // Parse the input
    unsigned choice;
    if (sscanf(input, "%u", &choice) != 1)
    {
        printf("Input was not a number\n");
        continue;
    }

    // See if the input was valid
    if (choice != 1 && choice != 2)
    {
        printf("Input was not a valid choice, please try again\n");
        continue;
    }

    // By this point the input and its validation was successful,
    // don't loop anymore
    break;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 2012-12-08
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    相关资源
    最近更新 更多