-2

So I'm a beginner to programming and thought I would try and make a basic calculator that gives the sum or product of two numbers. However, in the while loop of this program, the first printf seems to print twice after the first iteration of the loop. Any help rectifying this would be greatly appreciated.

#include <stdio.h>
#include <string.h>

int multiply(int a, int b) {
    return a * b;
}

void printMultiply(int x, int y) {
    int result = multiply(x, y);
    printf("\n%d\n", result);
}

int add(int a, int b) {
    return a + b;
}

void printAdd(int x, int y) {
    int result = add(x, y);
    printf("\n%d\n", result);
}

int main() {
    int product1 = 0;
    int product2 = 0;

    int sum1 = 0;
    int sum2 = 0;

    while (true) {
        // this prints twice after first iteration?
        printf("Would you like to add or multiply? (press a or  m)\n");

        char choice = ' ';
        scanf("%c", &choice);

        if (choice == 'm') {
            printf("What two numbers would you like to multiply? (leave a space between numbers\n");
            scanf("%d%d", &product1, &product2);
            printMultiply(product1, product2);
        } else
        if (choice == 'a') {
            printf("What two numbers would you like to add?  (leave a space between numbers\n");

            scanf("%d%d", &sum1, &sum2);
            printAdd(sum1, sum2);
        }
    }
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Njgardner90
  • 61
  • 1
  • 7
  • you probably hit the linefeed from the scanf, since it doesn't fall in your known choices it loops. – Jean-François Fabre Sep 17 '17 at 20:17
  • `scanf(...)` is reacting to an unseen return character. Try putting a space character in front of the format string to consume the `return` (_newline_) character: `scanf(" %c", &choice);` – ryyker Sep 17 '17 at 20:21

3 Answers3

3

After the first iteration, you're seeing a newline (\n) in your first call to scanf.

All you need to do is use a leading space in your format string to eat up any whitespace:

scanf(" %c", &choice);
user94559
  • 59,196
  • 6
  • 103
  • 103
  • That is strange for me to understand. I had this working using std::cin with no problems, which is what threw me. So pressing 'enter' after the two numbers means scanf automatically reads \n the next time round? – Njgardner90 Sep 17 '17 at 20:40
  • Yes. You need to consume the newline character somewhere. It's a common gotcha with `scanf`. – user94559 Sep 17 '17 at 20:42
0

'\n' is entered to ch after 1st iteration. remove it from buffer.

scanf("%d%d", &sum1, &sum2);

scanf("%c", &enter);

Younghwa Park
  • 392
  • 2
  • 9
0

Try this:

scanf("\n%c", &choice);

This will sort out your problem.

Aashish Kumar
  • 2,771
  • 3
  • 28
  • 43