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?

7
  • 1
    do not add spaces (tabs, newlines, ...) after "%d" (or "%c" or "%[]" or "%s"...) in scanf. Even better: stop using scanf for user input. Commented Apr 4, 2020 at 8:34
  • 2
    scanf(" %d \n", &el1); should be scanf("%d", &el1); Commented Apr 4, 2020 at 8:34
  • Now el1 and el2 work, but my program doesn't read op[0]. Commented Apr 4, 2020 at 8:46
  • @kasiab do what pmg said. Use a space before %c Commented Apr 4, 2020 at 8: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. Commented Apr 4, 2020 at 8:47

1 Answer 1

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]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.