0

I am making a calculator where the user inputs something like, 'sum 3 4' and it would print '7'.

I have an infinite looping going and it scans for three things: a string and two ints. It all works except when you click enter, the terminal just makes a newline, and it keeps doing this until you enter something else. If you run it you'll see what I mean.

for (;;) {
    scanf("%20s", stringBuffer);
    scanf("%d ", &num1);
    scanf("%d ", &num2);

    if (strcmp(stringBuffer, "add") == 0) {
        printf("%d + %d = %d", num1, num2, (num1 + num2));
    } 
    else if (strcmp(stringBuffer, "sub") == 0) {
        printf("%d - %d = %d", num1, num2, (num1 - num2));

    }
    else if (strcmp(stringBuffer, "mul") == 0) {
        printf("%d * %d = %d", num1, num2, (num1 * num2));

    }
    else if (strcmp(stringBuffer, "div") == 0) {
        printf("%d / %d = %d", num1, num2, (num1 / num2));

    }
    else if (strcmp(stringBuffer, "help") == 0) {
        printf("input: operation n1 n2\n");
        printf("output: operation(n1, n2)\n");
        printf("implemented operations: 'add', 'sub', 'mul', and 'div'\n");
    }
    else if (strcmp(stringBuffer, "quit") == 0) {
        return 0;
    } else {
        printf("Please try again.\n");
    }
}

Any help towards a fix would be much appreciated.

Jake Jackson
  • 1,055
  • 1
  • 12
  • 34
  • 3
    `scanf(" ")` asks the program to *skip* whitespace so while you press space, tab, enter the program will be inside the scanf skipping what you press. `scanf("%d ")` means read an integer and skip whitespace. Try `scanf("%d")` – pmg Oct 25 '19 at 13:43
  • 3
    Output to `stdout` (which is where `printf` is writing) is by default *line buffered*. That means the buffer is *flushed* (actually written) when you print a newline. You print very few newlines so the results are simply not shown. – Some programmer dude Oct 25 '19 at 13:43
  • ... call `fflush(stdout)` right before your series of `scanf`s. – Jabberwocky Oct 25 '19 at 13:47
  • Don't include trailing white space in a `scanf()` format string. It is a UX disaster, as it requires the user to guess the correct next input before terminating the current input. Also, don't forget to check that `scanf()` succeeds — with erroneous input, it can report 0 as well as EOF if your format seeks to read a single value (as well as 1 indicating that it read one value successfully). – Jonathan Leffler Oct 25 '19 at 14:25

0 Answers0