2012-05-13 12 views
5

estoy tratando de crear un programa sencillo en C, donde el usuario tiene que elegir entre varias opciones:Cómo escribir un menú de consola en ANSI/ISO C?

char command = '1'; 
while(command!='0') { 
    printf("Menu:\n"); 
    printf("1. First option\n"); 
    printf("2. Second option\n"); 
    printf("0. Exit\n"); 
    printf("Choose: 0,1,2?: "); 
    command = getchar(); 
    while(getchar()!='\n');  
    switch(command) { 
     case '0': break; 
     case '1': functionCall1(); break; 
     case '2': functionCall2(); break; 
    } 
} 

El problema con mi código es, que cada vez que entro en la segunda 1,2 ó 0, no pasa nada, solo el menú se imprime de nuevo. Con el depurador puedo ver que el valor de comando, después de command = getchar() es igual a '', cada segundo tiempo. Pensé que comer el personaje de la nueva línea es suficiente?

+2

Su ejemplo se ejecuta bien para mí como es, y si tengo functionCall1 y functionCall2 imprimir algo, puedo ver que funciona como se anuncia. ¿Pero tal vez sea diferente con tu compilador? –

+3

El tipo de 'comando' debe ser' int' no 'char', para poder contener' EOF'. Tenga en cuenta que cuando alguien ingresa a EOF (por ejemplo, Ctrl-D en Unix), su programa gira en el ciclo 'while (getchar()! = '\ N');'. – Jens

+2

a 'do {...} while ('0'! = Comando);' sería una construcción más elegante – guga

Respuesta

1

Puede ser que usted debe tratar de utilizar int x como una clave para utilizar un comando deseable, puede ser así:

while(x != 0) 
{ 
    scanf("%d", &x); 
    switch (x) 
    { 
     printf("input '2' to...\n"); 
     printf("input '3' to...\n"); 
     printf("input '4' to...\n"); 
     printf("input '5' to...\n"); 
     printf("input '6' to...\n"); 
     case 1: 
      head = Enqueue(head); 
      break; 
     case 2: 
      head1 = spisokMagazinovScenoiMensheiZadannoi(head, head1); 
      break; 
     case 3: 
      head1 = udalenieElementa(head1); 
      break; 
     case 4: 
      head1 = addNewMagazin(head1); 
      break; 
     case 5: 
      head1 = addNewMagazin(head1); 
      break; 
     case 6: 
      printToTheFile(head); 
      break; 

    } 
} 

que utilizaban en mi tarea anterior. Espero que sea útil para usted

3

Pruebe mi menú personalizado, lo implementé para hacer mi vida más fácil cuando trabajo con programas que contienen operaciones de múltiples opciones. El menú es navegable (flechas: arriba, abajo, izquierda, derecha), y para hacer una selección solo necesita presionar la tecla enter, la orientación del menú puede establecerse vertical u horizontalmente, el relleno puede configurarse como un grupo de elementos (para niños) , posición de partida del niño y actualización con retraso.

ejemplo Llamada del menú (vertical):

int response = menu("OPTIONS","[*]","->", 
        1,3,3,0,5, 
        "PROFILES","ACTIVITY","VIDEO","SOUND","GAMEPLAY"); 

Lo más importante es porque implementación de la función tarda sólo 60 líneas de código.

aplicación Menú:

#include <stdio.h> 
#include <stdlib.h> 
#include <stdarg.h> 
#include <windows.h> 

// LXSoft 
// mod: cui/menu_021 
// stdarg.h -> used for variable list of arguments (va_list, va_start ...) 
// windows.h -> used for Sleep function, for *nix use unistd.h 

typedef unsigned short int usint_t; 
// Menu function prototype 
int menu(char* name, char* prefix, char* cursor, usint_t orientation, 
     usint_t padding, usint_t start_pos, usint_t delay, 
     usint_t num_childs, ...); 

int main() 
{ 
    int response = menu("OPTIONS","[*]","->",1,3,3,0,5, 
         "PROFILES","ACTIVITY","VIDEO","SOUND","GAMEPLAY"); 
    switch(response) 
    { 
     case 1: 
      // doSomethingFoo1(); 
     break; 
     case 2: 
      //doSomethingFoo2(); 
     break; 
     /* 
     * . 
     * . 
     * . 
     * case n: 
     * break; 
     */ 
    } 
    printf("\nYour choice is: %d", response); 
    return 0; 
} 

// Menu implementation 
int menu 
(
    char *name,  // Menu name (eg.: OPTIONS) 
    char *prefix,  // Menu prefix (eg.: [*]) 
    char *cursor,  // Menu cursor (eg.: ->) 
    usint_t orient, /* 
         * Menu orientation vertical or horzontal. 
         * 0 or false for horizontal 
         * 1 or true for vertical 
         */ 
    usint_t padding, // Menu childrens padding (eg.: 3) 
    usint_t start_pos, // Menu set active child (eg.: 1) 
    usint_t delay,  // Menu children switch delay 
    usint_t childs, // Number of childrens 
    ...    /* 
         * Variable list of arguments char* type. 
         * Name of the childrens. 
         */ 
) 
{ 
    va_list args; 
    int tmp=0,pos; 
    char chr; 
    usint_t opt=start_pos; 
    char* format=malloc 
    (
     (
      strlen(name)+strlen(prefix)+strlen(cursor)+ 
      3+ /* menu suffix (1 byte) and backspace (2 bytes) */ 
      (2*childs)+ /* newline (2 bytes) times childs */ 
      (padding*childs)+ /* number of spaces times childs */ 
      childs*15 /* children name maxlen (15 bytes) times childs*/ 
     )*sizeof(char) 
    ); 
    do 
    { 
     if(tmp!=0)chr=getch(); 
     if(chr==0x48||chr==0x4B) 
      (opt>1&&opt!=1)?opt--:(opt=childs); 
     else if(chr==0x50||chr==0x4D) 
      (opt>=1&&opt!=childs)?opt++:(opt=1); 
     else {/* do nothing at this time*/} 
     strcpy(format,""); 
     strcat(format,prefix); 
     strcat(format,name); 
     strcat(format,":"); 
     va_start(args,childs); 
     for (tmp=1;tmp<=childs;tmp++) 
     { 
      (orient)?strcat(format,"\n"):0; 
      pos=padding; 
      while((pos--)>0) strcat(format," "); 
      if(tmp==opt) 
      { 
       strcat(format,"\b"); 
       strcat(format,cursor); 
      } 
      strcat(format,va_arg(args,char*)); 
     } 
     /*if(tmp!=childs) 
     { 
      fprintf(stderr,"%s: recieved NULL pointer argument," 
          " child not named", __func__); 
      return -1; 
     }*/ 
     Sleep(delay); 
     system("cls"); 
     printf(format); 
     va_end(args); 
    }while((chr=getch())!=0x0D); 
    return opt; 
} 
+0

¡muy bonito! Merece aprender la implementación. –

Cuestiones relacionadas