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?