somers
somers

Reputation: 51

C Programming help - providing user with option to exit a program

I've written a program to compute the running sum of any numbers input by a user. I need to provide the user with an option to exit the program at any stage, which I'm not sure how to do. I was looking into it and think getchar() is what I need to use but I'm not sure, there seem to be a few ways to do it.

I basically want the user to be able to hit "e" on the keyboard if they want to exit the program, and it will terminate. The comments in the code are just ideas I had so I've left them there. Help appreciated, thanks. Code:

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

int main()
{
     float number;
     float sum = 0;
     int i = 1;

     //char exit [2] = {'e'};
     //void exit (int status);

     printf ("Please enter number or enter \"e\" to exit at any stage:\n");
     scanf ("%f", &number);

       // if user inputs string e, program will terminate
       /* if (number == 'e')
          {
          printf ("Exiting the program...\n");
          exit(0);
          }                                       */

     while (i == 1)
     {
        sum += number;
        printf ("Sum: %.2f\n", sum);
        printf ("Please enter number:\n");
        scanf ("%f", &number);

        // if user inputs string e, program will terminate
        /*    if (number == 'e')
              {
                 printf ("Exiting the program...\n");
                 exit(0);
              }                                         */
     }

    return 0;
}

Upvotes: 0

Views: 2466

Answers (1)

BLUEPIXY
BLUEPIXY

Reputation: 40155

replace

scanf ("%f", &number);

to

if(1!=scanf ("%f", &number)){
    if (getchar() == 'e'){
        printf ("Exiting the program...\n");
        exit(0);
    }
}

Upvotes: 1

Related Questions