Search code examples
cscanf

first scanf gets other chrachters for the next scanfs


I'm making a simple calculator in C and I want the program to show the message "Enter an operator!" when the user enters something that isn't an operator, enter, space or tab. but if the user enters a number like 123 the message is shown 3 times instead of once. how can I fix this?

char op;
printf("please choose an operator (+,-,*,/): ");
while (op!='+' && op!='*' &&op!='-' &&op!='/' )
    {
    if (op!='\n'&& op!= '\t'&& op!=' ')
    printf ("Enter an operator!\n");
    scanf ("%c",&op);
    }

Solution

  • A scan set could be used %1[+-/*] will scan one character in the set of operators.
    If the character is not in the set, scanf will return 0. Clean the input stream and try again.

    #include <stdio.h>
    #include <stdlib.h>
    
    int main ( void) {
        char op[2] = "";
        int result = 1;
    
        printf ("Enter an operator!\n");
        do {
            if ( result != 1) {
                printf ("Enter an operator!\n");
            }
            result = scanf ( "%1[+-/*]", op);
            if ( result == EOF) {
                fprintf ( stderr, "EOF\n");
                return 1;
            }
            int clean = 0;
            while ( ( clean = fgetc ( stdin)) != '\n') { // clean input stream
                if ( clean == EOF) {
                    fprintf ( stderr, "EOF\n");
                    return 1;
                }
            }
        } while ( result != 1);
    
        printf ( "operator %s\n", op);
    
        return 0;
    }