简体   繁体   中英

How to enter a letter to quit a program in C

I am new to C programming. I have been writing this code to add numbers and I just need help with this one thing. When I type the letter 'q', the program should quit and give me the sum. How am I supposed to do that? It is currently the number 0 to close the program.

#include <stdio.h>
int main()

{

        printf("Sum Calculator\n");
        printf("==============\n");
        printf("Enter the numbers you would like to calculate the sum of.\n");
        printf("When done, type '0' to output the results and quit.\n");

   float sum,num;

   do  

   {                                    
        printf("Enter a number:");
        scanf("%f",&num);
        sum+=num;      
   }
  while (num!=0);


   printf("The sum of the numbers is %.6f\n",sum);

return 0;
}

One approach would be to change your scanf line to:

if ( 1 != scanf("%f",&num) )
    break;

This will exit the loop if they enter anything which is not recognizable as a number.

Whether or not you take this approach, it is still a good idea to check the return value of scanf and take appropriate action if failed. As you have it now, if they enter some text instead of a number then your program goes into an infinite loop since the scanf continually fails without consuming input.

It's actually not as straightforward as you'd think it would be. One approach is to check the value returned by scanf , which returns the number of arguments correctly read, and if the number wasn't successfully read, try another scanf to look for the quit character:

bool quit = false;
do
{                                    
    printf("Enter a number:");
    int numArgsRead = scanf("%f",&num);
    if(numArgsRead == 1)
    {
        sum+=num;
    }
    else // scan for number failed
    {
        char c;
        scanf("%c",&c);
        if(c == 'q') quit = true;
    }
}
while (!quit);

If you want your program to ignore other inputs (like another letter wouldn't quit) it gets more complicated.

The first solution would be to read the input as a character string, compare it to your character and then convert it to a number later. However, it has many issues such as buffer overflows and the like. So I'm not recommending it.

There is however a better solution for this:

char quit;
do  
{                                    
    printf("Enter a number:");
    quit=getchar();
    ungetc(quit, stdin);
    if(scanf("%f", &num))
            sum+=num;      
}
while (quit!='q')

ungetc pushes back the character on the input so it allows you to "peek" at the console input and check for a specific value.

You can replace it with a different character but in this case it is probably the easiest solution that fits exactly what you asked. It won't try to add numbers when the input is incorrect and will quit only with q .

@Shura

  1. scan the user input as a string.
  2. check string[0] for the exit condition. q in your case
  3. If exit condition is met, break
  4. If exit condition is not met, use atof() to convert the string to double atof() reference http://www.cplusplus.com/reference/cstdlib/atof/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM