C 编程帮助 - 为用户提供退出程序的选项

标签 c

我编写了一个程序来计算用户输入的任何数字的运行总和。我需要为用户提供在任何阶段退出程序的选项,但我不知道该怎么做。我正在研究它并认为 getchar() 是我需要使用的,但我不确定,似乎有几种方法可以做到这一点。

我基本上希望用户能够在想要退出程序时按下键盘上的“e”,然后程序就会终止。代码中的注释只是我的想法,所以我将它们留在那里。帮助表示感谢,谢谢。代码:

#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;
}

最佳答案

替换

scanf ("%f", &number);

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

关于C 编程帮助 - 为用户提供退出程序的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22391308/

相关文章:

c - 这两种代码有什么区别?

c++ - 套接字TCP服务器程序问题

跨平台(微 Controller -PC)算法开发

c - 在静态数组中存储二进制数据

c - 在给定为 void * 的 vector 内的结构内设置结构值

C 函数指针语法

c - Visual Studio 2010 问题中的链表

c - 当只有一个线程写入共享变量时,我需要锁吗?

c - 在 C 中使用 stat 检查文件是否可执行

检查位否定数中设置的位数是否为 2 或更多