-1
#include <stdio.h>


int multiple(int num1,int num2){
    return (num1*num2);
}

int add(int num1, int num2){
    return (num1+num2);
}
/*&x points to its value space *x points to its memory space*/
int main(){

    int num1,num2,ans;
    char func;

    printf("First number => ");
    scanf("%d",&num1);
    printf("Second number => ");
    scanf("%d",&num2);

    printf("Please Enter + for addition, or * for multiplication => ");
    scanf("%c",&func);

    if (func == '*'){
        ans = multiple(num1,num2);
    }else if(func == '+') {
        ans = add(num1,num2);
    }else {
        printf("Sorry, invalid operation");
    }

    printf("Ans : %d",ans);
    return 0;
}

When i run my programme it will prompt me for firest and the second number however it does not promts me for the char input scanf("%c",&func); is not being executed.

My ouput -----------------------------------------------------------------:

$ ./p8t3 First number => 23 Second number => 32 Please Enter + for addition, or * for multiplication => Sorry, invalid operationAns : 2665616

Termininja
  • 6,620
  • 12
  • 48
  • 49
KAKAK
  • 879
  • 7
  • 16
  • 32
  • I guess this would be the hundredth time this question has been asked like this one :http://stackoverflow.com/questions/1815986/does-scanf-take-n-as-input-leftover-from-previous-scanf/1816009#1816009 ............and this one http://stackoverflow.com/questions/7099209/why-scanf-is-behaving-weird-for-char-input/7099271#7099271 – 0decimal0 Jul 13 '13 at 17:45
  • Also this one :http://stackoverflow.com/questions/9441501/c-function-skips-user-input-in-code................................ and this one was asked just yesterday ::: http://stackoverflow.com/questions/17614761/calling-scanf-after-another-string-input-function-creates-phantom-input/17615082#17615082 – 0decimal0 Jul 13 '13 at 17:46

2 Answers2

3

while scanning for the + or * operator, change as below:

printf("Please Enter + for addition, or * for multiplication => ");
scanf(" %c",&func);         //use a space before '%c'
Nithin Bhaskar
  • 686
  • 1
  • 5
  • 9
  • 1
    this is working! thanks, although i am not sure what is the reasoning behind this.. edit: found the reasoning http://stackoverflow.com/q/14484431/2016977 – KAKAK Jul 13 '13 at 16:08
  • @DeepakTivari after the 2nd number is taken as input, the newline character is still present in the buffer. if you use scanf("%c", &func), it will read the newline character as input, thus causing erroneous beahviour. If you use scanf(" %c", &func), the scanf ignores the newline character and waits for the input from the user. – Nithin Bhaskar Jul 13 '13 at 16:15
1
printf("Please Enter + for addition, or * for multiplication => ");
scanf(" %c",&func);

The reason is that when you input a number and press ENTER, the scanf will process that number, but the new line is still in the input buffer.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294