tags:

views:

128

answers:

1

Hello,

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

-- Any idea why ?

Please help, thanks !!!!

+3  A: 

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);
}
Matthew Flaschen
Thank you very much Matthew !!!!This int status=0 was quite smart, thanks ! Didnt think of that.Oh and I want to add that using \n%c also stopped the echoing of Hello World twice .. THANKSCan you please explain more about the whitespace phenomenon ?Really appreciate your help, thank you very much !
ZaZu
Basically, when you type p and press enter, your program reads that as two characters 'P' and '\n' (I believe three, 'P', '\r', and '\n' on Windows). Without the whitespace in the scanf format string, the program tries to process the whitespace as a separate command.
Matthew Flaschen
+1 for explaining the use of `\n` in a `scanf` specifier.
Thomas Matthews
You're a legend, thank you !
ZaZu