Home > Mobile >  If statement is not working with char in C
If statement is not working with char in C

Time:10-14

I've been trying to make this if work I've tried to put scanf in every way possible and that was not the problem because it picks it up the " " is stored as I see it on the printf below. Can anyone figure out why not? Thanks

float number1;
float number2;
float total;
char operator[1];
printf("Welcome to the calculator\n");
while(3>2)
{
    printf("Pick a number\n");
    scanf("%f", &number1);
    
    printf("Que quieres hacer?\n");
    scanf(" %c", &operator);
    printf("You wrote %s\n", operator);
    
    if(operator ==' ')
    {
        printf("This works!");
    }
}

CodePudding user response:

This code snippet

    scanf(" %c", &operator);
    printf("You wrote %s\n", operator);
    
    if(operator ==' ')
    {
        printf("This works!");
    }

is incorrect independent on how the variable operator is declared.

If the variable operator is declared like

char operator;

then this statement

printf("You wrote %s\n", operator);

invokes undefined behavior.

In this case you need to write

printf("You wrote %c\n", operator);

If the variable operator is declared as a character array as for example

char operator[N];

where N is some value then at least this statement

if(operator ==' ')

does not make a sense and the condition will always evaluate to false.

Pay attention to that instead of this condition in the while loop

while(3>2)

it would be much simpler and readable just to write

while ( 1 )
  • Related