0

I am writing a simple calculator. I want to read first integer and save it in el1. Then I want to print "Enter el2: \n" and after this read the second integer and save it in el2. After this I need to print "Choose from ( + , - , / , * )" and read it and save in op[0]. My program is printing Enter el1: and then it waits for me to input 2 integers, then it pronts Enter el2: and waits for me to input 1 integer and then prints Choose from.. and reads nothing.

int el1 = 0;
printf("Enter el1:  \n");
scanf(" %d \n", &el1);
int el2 = 0;
printf("Enter el2: \n");
scanf(" %d \n", &el2);
printf("Choose from ( + ,  - ,  / , * ):\n");
char op[2];
scanf("%c", &op[0]);

How to make it work properly?

  • 1
    do not add spaces (tabs, newlines, ...) after `"%d"` (or `"%c"` or `"%[]"` or `"%s"`...) in scanf. Even better: stop using scanf for user input. – pmg Apr 04 '20 at 08:34
  • 2
    `scanf(" %d \n", &el1);` should be `scanf("%d", &el1);` – Weather Vane Apr 04 '20 at 08:34
  • Now el1 and el2 work, but my program doesn't read op[0]. –  Apr 04 '20 at 08:46
  • @kasiab do what pmg said. Use a space before %c – Abhay Aravinda Apr 04 '20 at 08:47
  • Ok, I added a space before %c, why now it works? I don't understand the logic of it.Edit; Thanks. I didn't see that comment. –  Apr 04 '20 at 08:47
  • Empty space is a characcter – Abhay Aravinda Apr 04 '20 at 08:48
  • Some explanation: most of the format specifiers for `scanf` automatically filter leading whitespace, but `%c` and `%[...]` and `%n` do not. Adding a space in front of the `%` instructs `scanf` to filter leading whitespace here too. Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). – Weather Vane Apr 04 '20 at 09:02

1 Answers1

1

as mentioned in comments remove white spaces from scanf .otherwise it will wait for you to enter a non-white space character.

and add one space here scanf(" %c", &op[0]); , because it prevent scanf to take \n in buffer as input.

look

printf("Enter el1:  \n");
scanf("%d", &el1);
int el2 = 0;
printf("Enter el2: \n");
scanf("%d", &el2);
printf("Choose from ( + ,  - ,  / , * ):\n");
char op[2];
scanf(" %c", &op[0]);
hanie
  • 1,863
  • 3
  • 9
  • 19