2014-09-26 48 views
-7

我已经能够执行开关盒程序,但是我希望程序一次又一次地运行,直到用户选择退出。 我基本上希望计划一次又一次用做while循环运行...C编程在开关盒程序中执行

switch(I) 
{ 
case 1: 
    printf("67"); 
    break; 
case 2: 
    printf("45"); 
    break; 
default: 
    printf("default"); 
} 
+5

好的,太棒了!什么不起作用?你使用什么代码?这*这是哪种语言? C#和Objective-C非常不同。 – BradleyDotNET 2014-09-26 16:35:53

+0

这是可能的,调查所有强大的*无限循环*。 – Greg 2014-09-26 16:37:56

回答

0

使用do...while循环是这样的:

int I = 1; //Initialize to some non-zero number to prevent UB 
printf("Enter 0 to quit \n"); 
do{ 
    if (scanf("%d",&I) != 1) //If invalid data such as characters are inputted 
    { 
     scanf("%*[^\n]"); 
     scanf("%*c"); //Clear the stdin 
    } 
} while(I!=0); //Loop until `I` is not 0 

这段代码中循环,直到用户输入0。您可以根据您的需要更改此代码。如果你想在你的switch这个,在scanf后复制你的发布代码。

0

这个程序运行,直到用户提供了输入0或负数...

#include<stdio.h> 

int main() 
{ 
    int I; 
    do 
    { 
     scanf("%d",&I); 
     switch(I) 
     { 
     case 1: 
     printf("67"); 
     break; 
     case 2: 
     printf("45"); 
     break; 
     default: 
     printf("default"); 
     } 
    } 
    while(I>0); 
     return 0; 
} 
1

循环将运行,直到你进入-1作为输入。

#include<stdio.h> 
int main() 
{ 
    int I; 
    do 
    { 
     puts("Enter -1 to quit"); 
     printf("Enter your choice: "); 
     scanf("%d",&I); 
     switch(I) 
     { 
      case 1: 
      printf("67\n"); 
      break; 
      case 2: 
      printf("45\n"); 
      break; 
      case -1: 
      puts("Bye"); 
      break; 
      default: 
      printf("default\n"); 
     } 
    }while(I != -1); 
    return 0; 
} 
0

简单使用Do-While循环。

选择是用户选择将被存储的变量,无论他是否要再次打印语句。

int choice; 
do{ 
    printf("\nHello World!"); //This is the task of the program (Replace it with your task) 
    printf("\nDo You Want to Print it again ? 1 Yes/0 No: "); 
    scanf("%d",&choice); 
}while(choice==1); //Loop will exit when choice gets value other than 1