Click here to Skip to main content
15,886,590 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to create a simple menu interface for my newly created program. After the user chooses option 2, how do I save his/her's name and include a return option to the main menu? After that, how can I include the name in the main program? The same goes for option 3.

I have included both the main code and the menu code below. Any advice and help would be greatly appreciated.

What I have tried:

The menu code:
#include <stdio.h>

int main()
{
int i1=1;
while (i1 != 0)
{
printf("    ********************** Welcome! *********************\n");
printf("    *                     Maths Quiz                    *\n");
printf("    * 1.Enter Quiz                                      *\n");
printf("    * 2.Enter Name                                      *\n");
printf("    * 3.Instructions                                    *\n");
printf("    * 4.Quit                                            *\n");
printf("    *****************************************************\n");
printf("Please choose one from 1-4:\n");
scanf("%d", &i1);

switch (i1)
{
case 1:
printf("Enter Quiz:\n");
i1 = 0;
break;
case 2:
printf("Enter Name:\n");
i1 = 0;
break;
case 3:
printf("Instructions:\n");
i1 = 0;
break;
case 4:
printf("Quit:\n");
i1 = 0;
break;
}
}
return 0;
}


The main code:
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX_TESTS 10

bool myread(const char* format, void* address)
{
    char buffer[1024];
    fgets(buffer, sizeof buffer, stdin);
    return sscanf(buffer, format, address) == 1;
}

struct struc {
    int a;

    int b;

    int c;

    int add;

    int grade;
};

int sj(int n)
{
    int t;

    t = rand() % n;

    return t;
}

void ctm_i(struct struc* t)
{
    t->a = sj(101);

    t->c = sj(4);

    if (t->c == 1) {
        t->b = sj(101 - (t->a));

        t->add = (t->a) + (t->b);
    }

    else {
        t->b = sj((t->a) + 1);

        t->add = (t->a) - (t->b);
    }

    t->grade = 0;
}

void tcm_i(struct struc* t, int n)
{
    int ad;
    
    printf(
        " ***********************************************************************"
        "*********\n");

    printf(
        " ......................................................................."
        ".........\n");

    printf(" Question %d\n\n", n + 1);

    printf(" You have 3 attempts for this question\n\n");
        
    if (t->c == 1)
        printf(" %d+%d= ", t->a, t->b);
    else
        printf(" %d-%d= ", t->a, t->b);
        
    myread("%d", &ad);

    if (ad == t->add)

    {
        t->grade = 10;

        printf("\n Very good, you earned 10 marks\n\n");
    }

    else {
        printf("\n Incorrect, you have 2 attempts remaining\n\n");

        myread("%d", &ad);

        if (ad == t->add)

        {
            t->grade = 7;

            printf("\n Good, you earned 7 marks\n\n");
        }

        else {
            printf("\n Incorrect, you have 1 attempt remaining\n\n");

            myread("%d", &ad);

            if (ad == t->add)

            {
                t->grade = 5;

                printf("\n Not bad, you earned 5 marks\n\n");
            }

            else {
                t->grade = 0;

                printf("\n Failure, 0 mark\n\n");

                printf("\n The correct answer is %d\n\n", t->add);
            }
        }
    }

    printf(
        " ......................................................................."
        ".........\n");

    printf(
        " ***********************************************************************"
        "*********\n");
}

int main()
{
    int rounds = 0;
    int highest = 0;
    int lowest = INT_MAX;
    float allScore = 0;
    float avg = 0;

    int i, j, g = 0;
    //char x;
    struct struc test[MAX_TESTS];

    srand((unsigned)time(NULL));

    printf(
        " ***********************************************************************"
        "************\n");

    printf(
        " ......................................................................."
        "............\n");

    printf(
        " ************************************* Welcome! ************************************\n");
   
    printf(" ......................This program is for students Grades 1-2......................\n");

    printf("\n Program description:\n");

    printf(
        "(1)10 questions are randomly generated, each question is worth 10 "
        "points;;\n");

    printf(
        "(2)Only addition and subtraction within 100 is allowed. The sum and the "
        "difference of the two numbers do not exceed the range of 0-100, negative "
        "numbers are not included.\n");

    printf("(3)There are 3 attempts for each question.;\n");

    printf(
        "(4)For each question, 10 points will be awarded for the first "
        "successful attempt, 7 points for the second attempt, and 5 points for "
        "the third attempt.\n");

    printf(
        "(5)At the end of the program, enter 'P' to start a new game, 'S' to show the results, and 'Q' to quit.;\n\n");

    printf(
        " ......................................................................."
        ".........\n");

    for (;;) {
        rounds++;
        printf(" ***********************************************************************"
        "*********\n");
                for (i = 0; i < MAX_TESTS; i++)              // generate all questions
                {
                        ctm_i(&test[i]);

                        for (j = 0; j < i; j++)

                                if (test[i].a == test[j].a && test[i].b == test[j].b && test[i].c == test[j].c)
                                        //if question is already present
                                        ctm_i(&test[i]);    //then re-generate
                }

                printf(" Are you ready? Please press any key to continue: ");
                int c;
                while ( (c = getchar()) != '\n' && c != EOF ) { }

        for (i = 1; i <= 5; i++) {
            printf(
                " *******************************************************************"
                "**"
                "***********\n");

            printf(
                " ..................................................................."
                ".."
                "...........\n");
        }

        // Take quiz
        for (i = 0; i < MAX_TESTS; i++)
            tcm_i(&test[i], i);

        printf(" End\n\n");

        bool done = false;
        bool unsure = true;
        bool showS = true;

        while (unsure) {
            unsure = false;
            puts("\n");
            if (showS) {
                                puts(" Enter 'S' to show results");
                        }
            puts(" Enter 'P' to play another round");
            puts(" Enter 'Q' to quit");
            char choice;
            myread("%c", &choice);
            if (choice == 'Q' || choice == 'q')
                done = true;
            else if (choice == 'S' || choice == 's') {
                                showS = false;
                                // calculate total score for current round
                                g = 0;
                                for (i = 0; i < MAX_TESTS; i++) {
                                                g += test[i].grade; //add score of each question
                                        }
                                allScore += g;  //add current round's score to total
                                avg = allScore / rounds;        //average of all rounds
                                
                                if (g > highest)
                                {
                                        highest = g;
                                }
                                
                                if (g < lowest)
                                {
                                        lowest = g;
                                }
                                
                if (rounds == 1)
                {
                    printf(" Final score: %d/100\n", g); //display round score
                }
                else {
                    //puts("Whoops! Looks like highest/lowest have not been adjusted!");
                    printf(" Round %d score: %d/100\n", rounds, g); //display round score
                    printf(" Highest score: %d/100\n", highest);
                    printf(" Lowest score: %d/100\n", lowest);
                    printf(" Average score: %f\n", avg);
                }
                unsure = true;
                //getchar();
            }
            else if (choice == 'P' || choice == 'p') {

            }
            else {
                puts(" Invalid input!");
                unsure = true;
            }
        }
        if (done)
            break;
    }
}
Posted
Updated 21-Nov-20 18:00pm

create a variable and then scanf into it
eg
C
int main()
{
    char name[30] = "";
    /* menu stuff ... */
    case 2:
        printf("Enter name");
        scanf("%s", name);
        break;
    /* etc */
}


But be aware that scanf("%s", name)only reads up to the next whitespace character on stdin, so if the user enters "Manic Dancer", then only "Manic" will be copied into the variable, leaving "Dancer" as the next token to be read in. It might be wiser to look into some other way of getting input from the user, like perhaps getline()
 
Share this answer
 
You need to organize your code into functions instead of having one big pile in main(). The initial main menu code should be in a function called that - InitialMenu or MainMenu or something like that. Then it generates questions, prints a header, and starts the quiz. The code for each item I listed should be in separate functions so you can easily call them where ever you want to have them. This means you will need a structure to contain all the data. You will have questions, answers, and the user's name as a start. You can pass this structure to each function that needs it. Your main function should be a series of calls to these functions with the looping that you want. You should be able to look at your main and see it all on one page so the flow of the program is clear at a high level. Think about things in functional terms like InitialMenu, PromptUser, GenerateQuiz, AdministerQuiz, DisplayResults, etc... and then organize the code into those functions. It doesn't literally have to fit on one page but that should be a target so you can clearly see what is going on.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900