0

I have make a program that take a number and a separator. If the user press enter, then the program will print the total of the number.

example input: 2[space]3[enter] will print "total = 5", 1[space]2[space]3[enter] will print "total = 6", but if I input 2a3[enter], the program will get terminated and exit instead of printing "error!" and the "press ENTER..." message. Previously, I use the system("PAUSE") function and there was no problem(the error message appear). And then I know that it is not standard, so I replace it with 2 lines of code(you can see it in the code) and the problem occur.

My input:

2[space]3[enter] --> print "total = 5"

2a3[enter] --> the program gets terminated instead of printing "error!" and the "press ENTER..." message

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num, total;
    char separator;

    for(;;)
    {
        scanf("%d%c", &num, &separator);
        total += num;

        if(separator == '\n')
        {
            printf("total = %d\n", total);
            break;
        }
        else if(separator == ' ')
        {
            //do nothing
        }
        else
        {
            printf("error!\n");
            break;
        }
    }

    printf("press ENTER to exit..."); //this
    getchar(); //two lines
    //previously, I use system("PAUSE"), and there is no problem.

    return 0;
}

I use gcc 10.3.0 and Windows 10 OS.

Can anyone explain to me why this problem occur?

  • 3
    Your `total` is uninitialized for starters... – Eugene Sh. May 19 '22 at 13:28
  • 2
    Also add a newline after `printf("press ENTER to exit...");` so it will get flushed right away. – Eugene Sh. May 19 '22 at 13:30
  • @Yunnosch I don't think there is a UB here (unless we consider printing indeterminate values UB). – Eugene Sh. May 19 '22 at 13:34
  • 1
    You should check the return value of `scanf`, because in case of failure (unexpected input) it won't populate your variables and these will be indeterminate too. – Eugene Sh. May 19 '22 at 13:36
  • What does "crash" mean here? I would assume that `getchar` consumes the second number and returns immediately. I expect it to just terminate but not to crash – Gerhardh May 19 '22 at 13:39
  • @Yunnosch There were few threads here on SO on the topic and I think the experts are divided. I'd say it's a UB, limited edition, as it can produce a limited number of possible outcomes, not including Nasal Demons :) – Eugene Sh. May 19 '22 at 13:40
  • 1
    @EugeneSh. & Yunnosch : [(Why) is using an uninitialized variable undefined behavior?](https://stackoverflow.com/q/11962457/2505965) – Oka May 19 '22 at 13:42
  • Try to replace `int num, total;` with `int num, total = 0;` and tell us if it works better – Jabberwocky May 19 '22 at 13:53
  • nope, the program gets terminated when I input 2a3, instead of printing "error!" message –  May 19 '22 at 13:56
  • Do you run it in a command window or some kind of IDE terminal? – Eugene Sh. May 19 '22 at 13:59
  • I use the command prompt to execute my code –  May 19 '22 at 14:04
  • 1
    I have reopened the question, as the proposed duplicate does not explain the described behavior. But this needs more information - please provide the full input/output view from your command window. – Eugene Sh. May 19 '22 at 14:05

1 Answers1

0

Input buffer fun.

When you hit the break; statement after the printf("error!"), there is a "3\n" in the input buffer; thus getchar() finds something to read immediately and thus your program appears to terminate immediately. The missing newline after error causes the line to be gobbled on Windows because the command prompt moves the cursor left first rather than starting the command prompt mid-line.

It is not recommended to use scanf to parse keyboard input but rather to use fgets() or getline() and parse yourself to avoid input buffer stuff like this.

Use of total like that is undefined, but it is improbable that you are using a processor that's going to fault here and I disregarded it.

Joshua
  • 40,822
  • 8
  • 72
  • 132
  • SOLVED! I add 'fflush(stdin)' above press enter line. Thanks! –  May 19 '22 at 14:34
  • 3
    @manungsa Even though `flush(stdin)` works on Windows, it's behavior is otherwise undefined by C standard, and you better avoid using it. See https://stackoverflow.com/questions/2979209/using-fflushstdin – Eugene Sh. May 19 '22 at 14:38