【问题标题】:BASIC Menu-driven program repeates twice after successful completion of first taskBASIC 菜单驱动程序在成功完成第一个任务后重复两次
【发布时间】:2010-05-03 19:44:12
【问题描述】:

我正在使用 Plato3 编写 C 程序。

我正在创建一个菜单驱动程序,但想测试让它工作的基本概念

#include<stdio.h>
#include<ctype.h>
int function1();

main(){
  char s;
 do{
   puts("\n choose the following");
   puts("(P)rint\n");
    puts("(Q)uit\n");
   scanf("%c",&s);
   s=toupper(s);
   switch (s){
     case 'P' : function1();
        break;
        case 'Q' : return -1;
     break;
    }
 }while (function1()==0);  
}

int function1(){
   printf("Hello World");
   return 0;
 }

问题是一旦function1()返回值0,整个程序就回显了……为什么?

示例:运行程序给出了这个:

Hello WorldHellow World
 choose the following
(P)rint

(Q)uit

Hello World
 choose the following
(P)rint

(Q)uit

-- 知道为什么吗?

请帮忙,谢谢!!!!

【问题讨论】:

    标签: c


    【解决方案1】:

    如果您选择 P,您将在该 case 语句中调用 function1。然后,由于您没有从 main 返回 -1 (您的循环可以退出的唯一方法),您将再次从循环条件中调用 function1。

    它在双 HelloWorld 和单 HelloWorld 之间交替的原因是空格字符不匹配 'P'。相反,他们只是被忽略了。为了解决这个问题,您可能想要丢弃空格,因此我们将 \n 添加到 scanf。我还为不正确的输入添加了默认情况,目前也退出了循环。所以你最终会得到类似的东西:

    main(){
        char s;
        int status = 0;
        do{
            puts("\n choose the following");
            puts("(P)rint\n");
            puts("(Q)uit\n");
            scanf("\n%c",&s);
            s=toupper(s);
            switch (s){
            case 'P' : status = function1();
                break;
            case 'Q' : status = -1;
                break;
            default : status = -1;
            }
        } while (status == 0);
    }
    

    【讨论】:

    • 非常感谢马修!!!!这个 int status=0 非常聪明,谢谢!没想到。哦,我想补充一点,使用 \n%c 也两次停止了 Hello World 的回声。谢谢你能解释一下空格现象吗?非常感谢您的帮助,非常感谢!
    • 基本上,当您键入 p 并按回车键时,您的程序会将其读取为两个字符 'P' 和 '\n'(我相信三个,'P'、'\r' 和 '\ n' 在 Windows 上)。如果 scanf 格式字符串中没有空格,程序会尝试将空格作为单独的命令处理。
    猜你喜欢
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 2018-07-22
    相关资源
    最近更新 更多