我编写了一个程序来计算用户输入的任何数字的运行总和。我需要为用户提供在任何阶段退出程序的选项,但我不知道该怎么做。我正在研究它并认为 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/