0

My aim was to select + or - sign and then add or subtract 2 numbers.

But I didn't understand why after the entrance of the first number, it only prompts to enter operation sign but ignores to take input sign despite I didn't press a button.

#include<stdio.h>

main()
    {

    char sign;
    int no1, no2;
    int result= 0;

    printf("Enter first number:" );
    scanf("%d", &no1);
    printf("no1 is %d\n", no1);

    printf("\nEnter sign: '+' or '-' ");
    sign = getchar();

    printf("Enter second number: ");
    scanf("%d", &no2);
    printf("no2 is %d", no2);

    if(sign == '+')
    {
        result= no1 + no2;
    }
    else if(sign == '-')
        {
            result= no1-no2;
        }
        else
            {
                printf("Enter a valid sign!\n");
            }
    printf("%d\n", result);

    }
user175079
  • 1
  • 1
  • 4
  • 2
    Why don't you check what getchar did get? – Paul Ogilvie Jan 30 '18 at 14:32
  • see https://stackoverflow.com/questions/1798511/how-to-avoid-press-enter-with-any-getchar#1798833 – neuhaus Jan 30 '18 at 14:34
  • Note that [`getchar`](http://en.cppreference.com/w/c/io/getchar) returns an `int`. This is actually quite important if you want to compare the result to `EOF`. – Some programmer dude Jan 30 '18 at 14:34
  • @PaulOgilvie has given you a huge hint. Print it out (`printf("%d", sign)`) and look it up at asciitable.com :-) – wally Jan 30 '18 at 14:36
  • Okey. It takes value 10 which corresponding to new line character but why it took value earlier than 'printf("\nEnter sign: '+' or '-' ")' prompt even though it is after that prompt. What is happening ? – user175079 Jan 30 '18 at 15:30

0 Answers0