【问题标题】:fflush(stdin) not working in visual studio 2015 [duplicate]fflush(stdin)在visual studio 2015中不起作用[重复]
【发布时间】:2023-04-04 11:04:01
【问题描述】:

此代码不像在 CodeBlocks 中那样工作:

#include <stdio.h> 
#include <stdlib.h>

int main()
{
    char c;
    char choice;

    do
    {
        printf("Enter a character using getchar(): ");
        fflush(stdin);
        c = getchar();
        printf("The entered charcter is: ");
        putchar(c);
        do
        {
            printf("\nDo you want to continue [Y/N]: ");
            fflush(stdin);
            choice = getchar();
            if (choice >= 'a' && choice <= 'z')
                choice -= 32;
        } while (choice != 'Y' && choice != 'N');
        printf("\n");
    } while (choice == 'Y');

    system("pause");
    return 0;
}

输出是:

Enter a character using getchar(): !
The entered character is: !
Do you want to continue [Y/N]:
Do you want to continue [Y/N]: y

Enter a character using getchar(): The entered character is:

Do you want to continue [Y/N]:

为什么 fflush(stdin) 不起作用?

有没有其他办法解决这个问题?

【问题讨论】:

    标签: c visual-studio


    【解决方案1】:

    fflush(stdin) 未定义,按照标准:

    J.2 未定义的行为

    fflush 函数的流指向输入流或更新流,其中输入了最近的操作 (7.21.5.2)。

    所以不要使用它。

    【讨论】:

    • fflush(stdin) 的其他替代方案?
    • 额外的getchar() 将为您获取\n
    • 那么有没有办法只获取输入而不是 \n???
    猜你喜欢
    • 2015-06-26
    • 2018-06-15
    • 2012-02-25
    • 2012-12-27
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    相关资源
    最近更新 更多