开发者

BASIC Menu-driven program repeates twice after successful completion of first task

开发者 https://www.devze.com 2022-12-29 14:48 出处:网络
Im using Plato3 to write C programs. Im creating a menu-driven program but want to test out the basic concept of getting it to work

Im using Plato3 to write C programs.

Im creating a menu-driven program but want to test out the basic concept of getting it to work

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

The problem is that once function1() returns the value 0, the whole program is echoed ... why ?

Example : Running the program gives this :

Hello WorldHellow World
 choose the following
(P)rint

(Q)uit

Hello World
 choose the following
(P)rint

(Q)uit

-- 开发者_C百科Any idea why ?

Please help, thanks !!!!


If you select P, you will call function1 in that case statement. Then, since you have not returned -1 from main (the only way your loop can exit), you will then call function1 again from the loop conditional.

The reason it alternates between double HelloWorld and single is that whitespace characters are not matched by 'P'. Instead, they were simply ignored. To deal with this, you probably want to discard whitespace, so we add \n to the scanf. I also added a default case for incorrect input, which currently also exits the loop. So you end up with something like:

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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消