-2

I don't know what is wrong wiht my program, i tried to enter the numbers from keyboard and enter any operator and sort them like "a+b", but I don't know if it is correct so far, I don't have errors, but when I enter an operator it shows "You did not enter an opperator" it goes straight to the else, I don't know why. If you could please help me, thank you!

int main()
{
    int a, b;
    int op;
    int var = '+';
    int var1= '-';
    int var2= '/';
    int var3= '*';
    printf("Choose your 2 numbers: ");
    scanf("%i", &a);
    scanf("%i", &b);
    printf("Choose your operator (+, -, *, /): ");
    scanf("%i", &op);
    
    if(op == var || op == var1 || op == var2 || op == var3)
    {
        printf("The correct order is: %i, %i, %i", a, op, b);
    }
    else
    {
        printf("You did not enter an operator"); 
    }
    
    return 0;
}
  • Can you provide some test input, and its expected/actual output? – sup39 Oct 17 '20 at 21:47
  • 1
    Maybe you should define your operator as a char and also read a char from stdin instead of an integer with %c. That might solve already some conversion errors. – hamon Oct 17 '20 at 21:47

1 Answers1

0

So, first of all it'd be better to declare your op variable as a char instead of int as you are trying to read a character from the keyboard and not an integer number. Indeed if your try to print out your op variable as it is in your code you'll find out that its value is 0.
After changing this you should also change all %i for that variable to %c. This though will give a problem when using scanf(), which is that it will look like it got skipped. This is because the scanf() will read the last \n from the user as the character and put it in your variable.
To fix this you just need to put a space before %c so that the scanf() will skip the first whitespace character and then read from the keyboard. You can find more detailed explanation about this here
Anyway down here there's the working code.

int main()
{
    int a, b;
    char op;
    int var = '+';
    int var1 = '-';
    int var2 = '/';
    int var3 = '*';
    printf("Choose your 2 numbers: ");
    scanf("%d", &a);
    scanf("%d", &b);

    printf("Choose your operator (+, -, *, /): ");
    scanf(" %c", &op);

    if(op == var || op == var1 || op == var2 || op == var3)
    {
        printf("The correct order is: %i, %c, %i", a, op, b);
    }
    else
    {
        printf("You did not enter an operator."); 
    }

    return 0;
}
CrystalSpider
  • 377
  • 7
  • 16