繁体   English   中英

如何使用 switch 和 case 在 C [暂停] 中创建菜单

[英]How can I use switch and case to create a menu in C [on hold]

我正在尝试在 C 中创建一个菜单,该菜单使用开关和大小写来有效导航。

我可以到达第一个子菜单,但在输入值后它也会打印顶部菜单。 我还需要知道如何定义输入的内容,这样我就知道老师是否想输入课程作业 1、2 或 3 的数据。

我将如何 go 这样做?

提前谢谢你。

编辑:

我有一些基本的函数知识,但不足以使用 arrays 和指针,听起来它工作得很好并且是一个优雅的解决方案。

这是完整的代码。 同样,我刚刚开始学习如何使用 C 并对任何草率的代码表示歉意。

int main(void)
{
    /* Function Prototypes */
int menu;
int opt1;

menu = 0;
while (menu !=4)
{
/*Display menu with 4 numbered options:*/
printf("\n     Main Menu\n");
printf("\n Type a number to enter your choice.\n");
/*1. Enter Marks*/ 
printf("\n\n1. Enter Marks\n");
/*2. Display a particular students marks*/
printf("2. Display Specific Stucdents Mark\n");
/*3. Supervisor mode*/
printf("3. Supervisor Mode\n");
/*4. Exit program*/
printf("4. Exit Program\n\n");
printf("Enter option: \n");
scanf("%d", &menu);
while (menu > 4 || menu < 1)
{
    printf("Error, please enter a valid option\n");
    scanf("%d", &menu);
}



switch (menu)
{
    case 1:
        {
        system("cls");
        printf("1. Enter Marks\n");
        printf("2. Return to menu\n");
        scanf("%d", &opt1);
        if (opt1 = 1)
        switch (opt1)
        {
            case 1:
                {
                    printf("Is the mark for coursework 1, 2 or 3?");
                }
        }
        /*Are the marks for course work 1, 2 or 3?*/
        /*Enter Marks*/
        /*Display results table*/
        /*Option to edit*/
        /*Confirm and return to menu*/
        }

列出你错了的几件事:

scanf("%d", &j);

您必须测试scanf的返回值。 它会告诉你它是否读取了一个有效的数字。

printf("Please enter the number of students...);
scanf("%d", &j);  // so j holds the number of students
...
name=(char*)calloc(j, sizeof(char));

您刚刚分配了j字符 我不认为那是你想要的。 你到底想要什么?

    scanf("%s",&name[i]);

这是什么? 您尝试将字符串读入单个字符? 再说一遍,你想要什么? 如果你想读取所有学生的名字,你应该从分配一个字符串数组开始,并为每个字符串分配 memory,例如:

char **name= malloc(j*sizeof(char *));
for (int i= 0; i<j; i++) {
    name[i]= malloc(80); // allocate 80 charrs for each name
    printf("Enter name for student %d:\n", i+1);
    scanf("%80s", name[i]);
}

你应该让你的菜单循环:

do {
    printmenu();
    menu= 0;
    if (scanf("%d", &menu)==1) {
        switch (menu) {
            case 1: ....; break;
            case....
            default:...
       }
    }
} while (menu !=0);

请注意, if (opt1 = 1)会将 1分配opt1 我想你的意思是if (opt1==1)

至今; rest 适合您。

(注意:出于学习的兴趣,我没有提供高级解决方案;仅提供基础知识。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM