gpt4 book ai didi

c - C中按0退出

转载 作者:行者123 更新时间:2023-11-30 21:37:08 25 4
gpt4 key购买 nike

int main()
{
int program = 0;
while (program >= 0)
{
printf("\nChoose one of the following programs: \n\n (1) Fibonacci Sequence Calculator \n (2) Decimal and Binary Calculator \n (3) Prime Number Calculator \n \nIf you want to exit the program, press (e).\nYour choice: ");

scanf("%d", &program);

if (program == 0)
{
printf("Quitting the program...\n\n");
return 0;
}

else if(program==1)
{
printf ("FIBONACCI SEQUENCE CALCULATOR");
}
else if(program==2)
{
printf("DECIMAL AND BINARY CALCULATOR");
}

else if(program==3)
{
printf("PRIME NUMBER CALCULATOR");
}

else
{
printf("ERROR");
}
}

当用户输入除0、1、2和3之外的任何内容时,我想打印“ERROR”,但这是我输入时的结果:

  • 除 0、1、2 和 3 之外的任何数字:“错误”(这是正确的)
  • 任何字母/符号:“退出程序...”(这应该是“错误”!)

也许这可以帮助我找到问题的答案:我已经知道 %d 用于扫描整数,%c 用于扫描字符。但是当我想扫描它们时我必须使用什么?

如有任何帮助,我们将不胜感激:)

最佳答案

示例其中一种方法。

#include <stdio.h>
#include <stdlib.h>

void end_proc(void){
printf("Quitting the program...\n\n");
exit(0);
}

void input_error_proc(void){
int ch;
printf("ERROR\n");
while((ch = getchar()) != '\n' && ch != EOF);//clear input
}

int main(void){
int program;

while(1){
printf("\n"
"Choose one of the following programs: \n\n"
" (1) Fibonacci Sequence Calculator \n"
" (2) Decimal and Binary Calculator \n"
" (3) Prime Number Calculator \n"
" \n"
"If you want to exit the program, press (e or 0).\n"
"Your choice: ");

if(1==scanf("%d", &program)){//input number
if (program == 0){
end_proc();
} else if(program == 1){
printf ("FIBONACCI SEQUENCE CALCULATOR");
} else if(program==2) {
printf("DECIMAL AND BINARY CALCULATOR");
} else if(program==3) {
printf("PRIME NUMBER CALCULATOR");
} else {
input_error_proc();
}
} else {//input not number
char ch, check;
if(2 == scanf(" %c%c", &ch, &check) && ch == 'e' && check == '\n')
end_proc();
else
input_error_proc();
}
}
return 0;
}

关于c - C中按0退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37622980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com