2012-05-13 6 views
5

나는 사용자가 몇 가지 옵션 중에서 선택할 수 있습니다 C에서 간단한 프로그램을 만들려고 해요 :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; 
    } 
} 

내 코드의 문제이고, 모든 두 번째로 내가 입력하는 것이 1, 2 또는 0, 아무 일도 일어나지 않고 메뉴 만 다시 인쇄됩니다. 내가 볼 수있는 디버거를 사용하면 의 값이이고, 명령 = getchar()은 매회 ''와 같다는 것을 알 수 있습니다. 개행 캐릭터를 먹는 것으로 충분하다고 생각했습니다.

+2

귀하의 예는 나를 위해 확인을 실행하고, 내가 functionCall1 및 functionCall2 인쇄 뭔가가 있다면, 나는 그것이 같은 광고 작동하는지 확인할 수 있습니다. 하지만 컴파일러에 따라 다를 수 있습니다. –

+3

'command'의 타입은'EOF'를 유지하기 위해서는'char'가 아닌'int'이어야합니다. 누군가 EOF (예 : Unix에서 Ctrl-D)를 입력하면 프로그램이 'while (getchar()! ='\ n ');'루프로 돌아갑니다. – Jens

+2

'do {...} while ('0 '! = 명령);'보다 세련된 구조가 될 것입니다 – guga

답변

1

당신이 그렇게 할 수있다, 바람직한 명령을 사용 키로 int x를 사용하는 것을 시도해야 할 수 있습니다 :

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; 

    } 
} 

나는 내 이전 숙제에 사용했다. 희망이 당신을 위해 유용 할 것입니다

3

여러 선택 작업이 포함 된 프로그램을 사용하여 작업 할 때 내 맞춤 메뉴를 시험해 보았습니다. 메뉴를 탐색 할 수 있습니다 (화살표 : 위, 아래, 왼쪽, 오른쪽). 선택을 위해서만 Enter 키를 눌러야합니다. 메뉴 방향은 수직 또는 수평으로 설정할 수 있고, 패딩은 항목 그룹 (어린이) , 자식 시작 위치 및 지연으로 업데이트합니다.

메뉴 호출 예 (수직)은 : 기능 구현 코드의 60 라인이 걸리기 때문에

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

가장 중요한 것은입니다.

메뉴 구현 :

#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

매우 좋습니다! 구현을 배울 자격이있다. –

관련 문제