【问题标题】:c - fflush or buffer cleanc - fflush 或缓冲区清理
【发布时间】:2021-12-19 08:23:43
【问题描述】:

我正在使用以下代码,当我选择“s”作为示例时,内部函数运行并且我在内部函数中使用 scanf("%d") 和空格键或输入在最后一个输入被保存为主要的下一个通道之后。在每个案例之后,我都尝试使用 fflush ,但这对我没有帮助。你们有什么建议吗? 秒问题是当我插入e时函数停止,但不打印BYE BYE消息

       #include "exe.h"
        #include <time.h>
        #include <stdlib.h>
        #include <stdio.h>
        
        int  main()
        {
            srand(time(NULL));
        //TODO: change the options
            char ch;
            do 
            {
                printMainOption(&ch);
                
                switch (ch)
                {
                    case 's':
                        q_subMat();
                        fflush(stdin);
                    break;
                         
                    case 'c':
            //funcC
                    break;
            
                    case 'b':
            //funcB
                    break;
            
                    case 'e':
  scanf("Bye Bye");
            fflush(stdin);
                    break;
            
                    default:
                        printf("The operator doesn't match any constant\n");
                
            }
        }while(ch!='e' || ch!='E');




void printMainOption(char *ch)
{
    printf("\n\nPlease choose one of the following options\n");
    printf("S/s - Biggest Matrix Sum\n");
    printf("C/c - Color Game\n");
    printf("B/b - Black And White Game\n");
    printf("E/e - Quit\n");
    scanf(" %c",ch);
    *ch=tolower(*ch);

}

【问题讨论】:

  • printMainOption 中有什么内容?我猜scanf("%c", ch);。在%c 之前放一个空格,所以scanf(" %c", ch); 会跳过前导空格。
  • 这能回答你的问题吗? scanf() leaves the new line char in the buffer
  • 可以分享printMainOption的功能吗??另一条评论,我们可以看到变量chchar 但你使用%d 来获取变量?尝试使用%c。更改这些内容后的另一个选项,在 scanf 函数上包含一个空格,例如 scanf(" %c", &amp;ch);
  • 在问题中包含了 printOption 函数。
  • 你不应该在只读FILE上使用fflush,解释here

标签: c char buffer fflush


【解决方案1】:

我已经解决了printMainOption 函数中的问题。

do ... while 修复了所有问题:

void printMainOption(char *ch) {
    printf("\n\nPlease choose one of the following options\n");
    printf("S/s - Biggest Matrix Sum\n");
    printf("C/c - Color Game\n");
    printf("B/b - Black And White Game\n");
    printf("E/e - Quit\n");
    do {
        scanf(" %c",ch);
        *ch=tolower(*ch);
    } while(*ch=='\n' || *ch==' ');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多