c - fflush or buffer clean

89 Views Asked by At

I'm using the following code, and when I'm picking 's' for an example, the inner function runs and Im using scanf("%d") in the inner function and the spacebar or the enter that comes after the last input is saved for the next ch in the main. I've tried to use fflush after every case but that didnt helped me. do you guys have any suggestions ? sec problem is that the function stops when im inserting e, but doesnt print the BYE BYE message

       #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);

}
1

There are 1 best solutions below

0
יונתן אליהו On

I've fixed the problem in the printMainOption function.

The do ... while fixed it all:

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==' ');
}