嘗試我的自定義菜單,我實現它,使我的生活更輕鬆,當我使用包含多項選擇操作的程序時。 菜單是可導航的(箭頭:向上,向下,向左,向右),並且爲了做出選擇,您只需要按下回車鍵,可以垂直或水平設置菜單方向,可以將填充設置爲一組項目(兒童) ,孩子的起始位置,並延遲更新。
菜單調用示例(垂直):
int response = menu("OPTIONS","[*]","->",
1,3,3,0,5,
"PROFILES","ACTIVITY","VIDEO","SOUND","GAMEPLAY");
最重要的事情是因爲功能的實現只需要60行代碼。
菜單實施方案:
#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;
}
你的榜樣運行對我來說沒原樣,如果我有functionCall1和functionCall2打印的東西,我可以看到它像宣傳的那樣。但是,編譯器可能有所不同嗎? –
'command'的類型必須是'int'而不是'char',以便能夠保存'EOF'。請注意,當有人輸入EOF(例如Unix上的Ctrl-D)時,程序會在while(getchar()!='\ n');'loop中旋轉。 – Jens
'do {...} while('0'!= command);'會是一個更優雅的構造 – guga