1

I wrote the following code (it is a caclulator which gets 1 of 3 operators (+/-/$) and 2 natural numbers (a,b) and calcultes (a op b) (a$b is defined to be a+(a+1)+...+(b-1)+b for a<=b and for a>b it is not defined):

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

int main() {

printf("Please choose an operation (+/-/$): ");
char op;
scanf("%c", &op);
while (op != '+' && op != '-' && op != '$') {
    printf("\nInvalid operation. Please choose again: ");
    scanf("%c", &op);
}
int a;
int b;
char term;
printf("\nPlease enter the first operand: ");
int scanCheck = scanf("%d%c", &a, &term);
while (scanCheck != 2 || term != '\n' || a < 0) {
    printf("\nInvalid number\n. Please enter the first operand: ");
    scanCheck = scanf("%d%c", &a, &term);
}
printf("\nPlease enter the second operand: ");
scanCheck = scanf("%d%c", &b, &term);
while (scanCheck != 2 || term != '\n' || b < 0) {
    printf("\nInvalid number\n. Please enter the first operand: ");
    scanCheck = scanf("%d%c", &b, &term);
}

if (op == '$' && a > b)
    printf("\nThe result is: Not Valid");

int result;
switch (op) {
case '+':
    result = a + b;
    break;
case '-':
    result = a - b;
    break;
case '$':
    result = 0;
    while (a <= b) {
        result += a;
        a++;
    }
    break;
}
printf("\nThe result is: %d", result);
return 0;
}

My problem is that when I run the program it prints nothing. However, after giving the program an input (e.g +, 3, 4) it prints the lines it should have printed earlier (with the correct result). Why does this happen? How can I fix this? FYI I'm using eclipse Juno with minGW compiler.

noamgot
  • 3,962
  • 4
  • 24
  • 44

2 Answers2

0

Output is line buffered. Add a newline at the end of any printout. Or flush the buffer explicitly using fflush(stdout);

For some reason many C programmers like to print newlines at the start of each printout. My advice would be not to do it that way. Just put the newline at the end of each printout, and you'll save yourself lots of trouble:

printf("The result is: %d\n", result);
Thomas Padron-McCarthy
  • 27,232
  • 8
  • 51
  • 75
0

You may want to add the '\n' at the end of your print statements instead of at the beginning: the buffers may not be flushed and will be delayed because of it.