简体   繁体   中英

While,switch, case statement

I'm using a while , switch , case statement for my menu and when it runs it keeps saying enter choice, I know while(1) creates an infinite loop but is there a way to avoid this?

while(1)
{
    printf("\nEnter Choice \n");
      scanf("%d",&i);
      switch(i)
      {
            case 1:
            {
             printf("Enter value to add to beginning: ");
             scanf("%c",&value);
             begin(value);
             display();
             break;
             }
             case 2:
             {
             printf("Enter value to add last: ");
             scanf("%c",&value);
             end(value);
             display();
             break;
             }
             case 3:
             {
             printf("Value to enter before\n");
             scanf("%c",&loc);

             printf("Enter value to add before\n");
             scanf("%c",&value);

             before(value,loc);
             display();
             break;
             }
             case 4 :
             {
             display();
             break;
             }

      }
}

Any help would be appreciated.

While(1) is ok. But you have to have some conditions to finish the loop. Like :

while(1){
.........
if(i == 0)
  break;
............
}

Add a space at the beginning of every "%d" and "%c",because scanf always leaves a newline characters in buffer:

"%d"->" %d" 
"%c"->" %c"

Alternative solution,

int i = !SOME_VALUE;

while(i != SOME_VALUE)
{
   printf("\n\nEnter Choice ");
   scanf("%d",&i);

    switch(i)
    {
        case SOME_VALUE: break;
         .
         .
         .
       // the rest of the switch cases
    }
}

SOME_VALUE is any integer number notify to stop loop.

Alternatively, you may want to put a condition in the loop that relates to the input, eg

do
{
    printf("\n\nEnter Choice ");
    scanf("%d",&i);
    // the rest of the switch is after this
} while (i != SOME_VALUE);

Note the use of the do loop, which tests the condition at the end, after a value has been read into i.

I would probably write a function that can be called in the loop:

while ((i = prompt_for("Enter choice")) != EOF)
{
     switch (i)
     {
     case ...
     }
}

And the prompt_for() function might be:

int prompt_for(const char *prompt)
{
    int choice;
    printf("%s: ", prompt);
    if (scanf("%d", &choice) != 1)
        return EOF;
    // Other validation?  Non-negative?  Is zero allowed?  Retries?
    return choice;
}

You can also find relevant discussion at:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM