How to enter a letter to exit the program in C

I'm new to C programming. I wrote this code to add numbers, and I just need help with this. When I type the letter "q", the program should exit and give me the amount. How am I supposed to do this? Currently, the number 0 is closing.

#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;
}
+4
source share
5 answers

One approach is to change the line scanfto:

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

This will exit the loop if they enter anything that is not recognized as a number.

, , - scanf , . , , , scanf , .

+2

, . - , scanf, , , scanf :

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);
+1

, :

do
{
  printf("Enter a number:");
  sum+=num;

} while(scanf("%f",&num));

, ( q), .

0

, (, ), .

, . , . .

:

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

ungetc , "" .

, , , , , . , , q.

0

@Shura

0
source

All Articles