Home > Software engineering >  first scanf gets other chrachters for the next scanfs
first scanf gets other chrachters for the next scanfs

Time:06-24

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

CodePudding user response:

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;
}

CodePudding user response:

For starters use the format string " %c" to enter a character. Pay attention to the leading space in the format string. It allows to skip white space characters as for example the new line character '\n'.

Pay attention to that you are using an uninitialized variable op in the condition of the while loop that results in undefined behavior.

char op;
printf("please choose an operator ( ,-,*,/): ");
while (op!=' ' && op!='*' &&op!='-' &&op!='/' )
//...

A simplified approach can look the following way

#include <stdio.h>
#include <string.h>

//...

char op;
printf("please choose an operator ( ,-,*,/): ");
const char *operations = " *-/";

while ( 1 )
{
    int result = scanf( " %c", &op );

    if ( result == 1 && strchr( operations, op ) != NULL )
    {
        break;
    }

    if ( result == 1 )
    {
        scanf( "%*[^\n]" );
    } 

    printf ("Enter an operator!\n");
}

CodePudding user response:

1st thing first. 1 rule I learned is that a function only do 1 thing. In your case, scanf("%c", &op) is being called multiple times. Put the scanf() between the while() loop and printf() and retry. You can use a do{...}while; loop too.

  • Related