如何制作一个在C中重复的菜单
How to make a menu that repeats in C
我正在用 C 编写一个文件压缩器程序,并且正在创建一个显示在程序开头的友好菜单。
这是简化的代码:
Compress.c
int main()
{
char directory[100];
char option;
bool exit = false;
do
{
printf("|------------------------------------|\n");
printf("| Welcome! |\n");
printf("| |\n");
printf("|Select one of the following options:|\n");
printf("| 1 - Compress a file |\n");
printf("| 2 - Decompress a file |\n");
printf("| 3 - Exit |\n");
printf("|------------------------------------|\n");
scanf(" %c", &option);
switch(option)
{
case '1':
printf("Enter the FULL directory or drag HERE the file you want to COMPRESS: \n");
scanf(" %s", directory);
/* COMPRESS FILE */
break;
case '2':
printf("Enter the FULL directory or drag HERE the file you want to UNCOMPRESS: \n");
scanf(" %s", directory);
/* DECOMPRESS FILE */
break;
case '3':
exit = true;
break;
default:
printf("Invalid option!\n\n");
break;
}
}while(exit == false);
return 0;
}
例如,在键入“1”并键入正确的目录后,程序会打印 10 次菜单和 returns0。但是当我键入无效或不存在的目录时,它会起作用,因为它仅打印 1 次菜单并等待用户再次键入选项!
为什么要这样做?
将scanf(" %s")
改成这个,成功了:
getchar();
gets(directory);
//AFTER READING THAT DIRECTORY, WE NEED TO CHECK IF IT HAS QUOTES ON IT:
if(directory[0] == '\"') //IF IT HAS, ENTER HERE
{
/* REMOVE ALL QUOTES IN THE DIRECTORY */
}
我正在用 C 编写一个文件压缩器程序,并且正在创建一个显示在程序开头的友好菜单。
这是简化的代码:
Compress.c
int main()
{
char directory[100];
char option;
bool exit = false;
do
{
printf("|------------------------------------|\n");
printf("| Welcome! |\n");
printf("| |\n");
printf("|Select one of the following options:|\n");
printf("| 1 - Compress a file |\n");
printf("| 2 - Decompress a file |\n");
printf("| 3 - Exit |\n");
printf("|------------------------------------|\n");
scanf(" %c", &option);
switch(option)
{
case '1':
printf("Enter the FULL directory or drag HERE the file you want to COMPRESS: \n");
scanf(" %s", directory);
/* COMPRESS FILE */
break;
case '2':
printf("Enter the FULL directory or drag HERE the file you want to UNCOMPRESS: \n");
scanf(" %s", directory);
/* DECOMPRESS FILE */
break;
case '3':
exit = true;
break;
default:
printf("Invalid option!\n\n");
break;
}
}while(exit == false);
return 0;
}
例如,在键入“1”并键入正确的目录后,程序会打印 10 次菜单和 returns0。但是当我键入无效或不存在的目录时,它会起作用,因为它仅打印 1 次菜单并等待用户再次键入选项!
为什么要这样做?
将scanf(" %s")
改成这个,成功了:
getchar();
gets(directory);
//AFTER READING THAT DIRECTORY, WE NEED TO CHECK IF IT HAS QUOTES ON IT:
if(directory[0] == '\"') //IF IT HAS, ENTER HERE
{
/* REMOVE ALL QUOTES IN THE DIRECTORY */
}