-1

I am creating a program that allows the user to enter a number. It then adds, subtracts, divides or multiplies consecutively on the first number entered and also exits when x is pressed.

My code:

    char o;
    float N1,N2,res;
    printf("Enter a Number Then Hit Enter> ");
    scanf("%f",&N1);
    res = N1;
    printf("\n****Value = %f****\n",res);

    while(1) {
        printf("\nEnter an operation (+,-,*,/) or enter (x) to exit Then Hit Enter> ");
        scanf("%*c%c",&o);

        if(o=='x') {
            break;
        }

        printf("Enter a Number Then Hit Enter> ");
        scanf("%f",&N2);

        switch(o) {
        case '+':
            res=res+N2;
            printf("\n****Value = %f****\n",res);
            break;
        case '-':
            res=res-N2;
            printf("\n****Value = %f****\n",res);
            break;
        case '*':
            res=res*N2;
            printf("\n****Value = %f****\n",res);
            break;
        case '/':
            res=res/N2;
            printf("\n****Value = %f****\n",res);
            break;

        default:
            printf("Illegal Operation Symbol ....Try again > ");
        }
    }
    enter code here
    return 0;
}

I want to know how to exit the program and if there is something missing?

Jonny Henly
  • 4,023
  • 4
  • 26
  • 43

1 Answers1

1

How to terminate a program by typing a letter?

IMHO, your original program should terminate correctly. However,if you are trying to exit the program only on a key-press(This option will help you retain the output window as in the case of Visual Studio), you could do something like below :

Substitute:

enter code here

with

while(getchar()!='\n')
   continue; //wasting the buffer
printf("You have pressed the x option\n");
printf("Press any key to exit..")
getchar();
sjsam
  • 21,411
  • 5
  • 55
  • 102