简体   繁体   English

如何在C中输入退出程序的信件

[英]How to enter a letter to quit a program in C

I am new to C programming. 我是C编程的新手。 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. 当我输入字母'q'时,程序应该退出并给我总和。 How am I supposed to do that? 我该怎么做? It is currently the number 0 to close the program. 目前是关闭该计划的数字0。

#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: 一种方法是将您的scanf行更改为:

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. 无论您是否采用这种方法,检查scanf的返回值仍然是一个好主意,如果失败则采取适当的措施。 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. 正如你现在所拥有的那样,如果他们输入一些文本而不是数字,那么你的程序会进入无限循环,因为scanf在不消耗输入的情况下连续失败。

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: 一种方法是检查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);

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. ungetc推回输入上的字符,这样它就可以“窥视”控制台输入并检查特定值。

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 . 当输入不正确时它不会尝试添加数字,并且仅在q时退出。

@Shura @Shura

  1. scan the user input as a string. 将用户输入扫描为字符串。
  2. check string[0] for the exit condition. 检查字符串[0]的退出条件。 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/ 如果不满足退出条件,请使用atof()将字符串转换为double atof()参考http://www.cplusplus.com/reference/cstdlib/atof/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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