-1

I am new to C++ and am currently enrolled in an intro class. I am creating a program that is a programming tutorial (the irony!) and currently am trying to add a menu option that will take the user to a quiz. Nothing fancy. As of right now, it seems like my functions are not recognizing a class I created. Here's what I have so far, any (very dumbed down) advice would be most appreciated!

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

int main()
{
    string username = "";
    int choice;
    char c;
    char answer;
    int x = 4;
    int y = 5;
    int z = x + y;
    int ans;
    int total;
    
    class Question
    {
    private:
        string Question_Text;
        string Answer_one;
        string Answer_two;
        string Answer_three;

        int Correct_Answer;
        int Question_Score;

    public:
        void setValues(string, string, string, string, int, int);
        void askQuestion ( );
    };

    //welcome message
    cout << "Hello user, please enter your name:";
    cin >> username;
    cout << "Welcome to the programming tutorial " << username << "."<< endl;

    //menu selection
    while(toupper (choice != 'E'))
    {
        cout << "What would you like to do? (Unit 1 - Declaring Variables (1), Unit 2 - Input/ Output (2), Unit 3 - Conditionals (3), Quizzes (4) or Exit (E))";
        cin >> choice;
        if (choice == '1')
        {
            cout << "We will begin with defining variables. The first step to doing this is choosing which datatype your variable is.\n";
            cout << "The following are a few of the common datatypes used in programming.\n";
            cout << "Character ==> char\n";
            cout << "Integer ==> int, long, double\n";
            cout << "Boolean ==> bool\n";
            cout << endl;
            cout << "When declaring a variable, you must put its datatype before the variable name.\n";
            cout << "An example of this would be if we wanted to declare the value of x as 4.\n";
            cout << "We would write this as: \n";
            cout << "int x = 4\n";
            cout << "The program will now use the value 4 for the variable name 'x'\n";
            cout << endl;
            cout << "Now let's assume we assigned the value of 5 to the variable 'y'\n";
            cout << "If we wanted to add x and y and assign the sum to the variable 'z', we would write:\n";
            cout << "int z = x + y\n";
            cout << "Now when we use the variable 'z' in our program, it will perform the calculation given x=4 and y=5 and declare 9 as the value of the variable 'z'.\n";
            cout << "To test our code, we would write: " << endl;
            cout << "cout<<'x + y'<< z << endl; \n";
            cout << "If written correctly, it will display as: \n";
            cout << "x + y = " << z << "." << endl;
            
        }
        if (choice == '2')
        {
            cout << "Now that we understand the basics of declaring variables, let's discuss displaying, or output of, information to a user.\n";
            cout << "If you wanted to display a welcome message, for example, you would type:\n";
            cout << "cout << 'Welcome';\n";
            cout << "The line of code would start with 'cout' followed by two less than signs and then the message you wish to display in quotes.\n";
            cout << "Using this, you can ask the user for input.\n";
            cout << "Enter c to continue...";
            cin >> c;
            cout << "Let's say we have a program that flips a coin. You may want to ask the user how many times to flip the coin.\n";
            cout << "Assuming we previously declared this amount variable as 'int timesFlipped', we would 'cout' our question and the next line would read:\n";
            cout << "cin>> timesFlipped; \n";
            cout << "This will store the users input for the variable 'timesFlipped'\n";
            cout << "You almost always end a line of code with a semi colon."<<endl;
        }
        if (choice == '3')
        {
            cout << "This unit will cover conditional expressions."<<endl;
        }
        if (choice == '4')
        {
            string Question_Text;
            string Answer_one;
            string Answer_two;
            string Answer_three;

            int Correct_Answer;
            int Question_Score;
            Question q1;
            Question q2;
            Question q3;
        
            
            cout <<username << ", you have chosen to take a quiz." << endl << endl;
            int ans, score = 0;
            cout << "Unit One Quiz - Variables " << endl << endl;

            q1.setValues("How would you declare the value of 'x' as 12? ",
                "x=12()",
                "x==12()",
                "x=12;()",
                3,
                1);
            q2.setValues("What do you need to put before a variable when declaring it?",
                "a name()",
                "a value()",
                "a datatype()",
                3,
                1);
            q3.setValues("Which data type would you use for a number that includes a decimal value?",
                "int()",
                "double()",
                "float()",
                2,
                1);

            q1.askQuestion();
            q2.askQuestion();
            q3.askQuestion();
            
            cout << "Your score out of a possible 3 is " << total << endl;

        }
        if (choice == 'E')
        {
            cout << "Have a good day!";
            break;
        }
    }


    system("pause");
}

void Question :: setValues(string q, string a1, string a2, string a3, int ca, int pa)
{
    string Question_Text;
    string Answer_one;
    string Answer_two;
    string Answer_three;

    int Correct_Answer;
    int Question_Score;
    
    Question_Text = q;
    Answer_one = a1;
    Answer_two = a2;
    Answer_three = a3;
    Correct_Answer = ca;
    Question_Score = pa;
}

void Question :: askQuestion()
{
    string Question_Text;
    string Answer_one;
    string Answer_two;
    string Answer_three;

    int Correct_Answer;
    int Question_Score;
    int ans;
    int Total;

    cout << endl;
    cout << Question_Text << endl;
    cout << "1. " << Answer_one << endl;
    cout << "2. " << Answer_two << endl;
    cout << "3. " << Answer_three << endl << endl;
    cout << "Please enter your answer: " << endl;
    cin >> ans;

    if (ans == Correct_Answer)
    {
        cout << "That is correct!" << endl;
        Total = Total + Question_Score;
    }
    else
    {
        cout << "Sorry, that is incorrect" << endl;
        cout << "The correct answer was " << Correct_Answer << endl;
    }
}

I declared the variables in both functions because it wasn't recognizing them in each until I did so, but now i'm thinking it is because the class isn't being recognized.

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48
dbrod
  • 11
  • 1
  • 6
    Just take your class outside of `main`. And don't redeclare member variables. – cigien Aug 28 '20 at 21:27
  • 2
    Variables with the same name in different scopes are still completely different and separate variables. They will not share the same value or anything. – drescherjm Aug 28 '20 at 21:30
  • 1
    @cigien: I do believe that's an answer. – einpoklum Aug 28 '20 at 21:35
  • Note: This is more "meta" than "irony". – user4581301 Aug 28 '20 at 21:35
  • 2
    Donna, @cigien has all but addressed the issue you're experiencing. However, in the future, please try to shorten your examples to a more screen-readable length - that often helps narrow the problem down. Also, when asking about compilation failure, it's important to explicitly specify the error you're getting and on which line. Finally - your question should have the form of a question (grammatically). Welcome to StackOverflow :-) – einpoklum Aug 28 '20 at 21:37
  • @cigien, thank you! I knew it was something very obvious! – dbrod Aug 28 '20 at 23:02
  • @einpoklum please explain to me how I would go about shortening this example if I do not know exactly which part of the code is giving me the issue? While my error messages were reading lines 171 and 175, the error was in the placement of my class at the beginning of the code. It seems to me that including the code in its entirety would be the most helpful approach. Finally, it appears as though everyone understood the intent of my question, but thanks for the grammar lesson! And the welcome. enjoy. my. grammar. pal. :) – dbrod Aug 28 '20 at 23:05
  • @DonnaBroderick: You would try cutting out parts of your code gradually - calculations, printing instructions, member variables etc - while keeping the error. Read more about this in our FAQ item on [Minimal Reproducible Examples](https://stackoverflow.com/help/minimal-reproducible-example). Luckily in your case, the issue with your code was fairly obvious. When this is not the case, you would likely get complaint comments and downvotes about "dumping" a large program for us to parse and not showing sufficient effort in solving the question yourself. – einpoklum Aug 28 '20 at 23:10

2 Answers2

3

Your program, for the purposes of the problem you're experiencing, can be whittled down into the following:

int main() 
{
    class Question  {
    public:
        void askQuestion();
    };

    Question q;
    q.askQuestion();
}

void Question::askQuestion() { }

You would get an error in the definition of Question::askQuestion(), since the class is declared (and defined) within the scope of the main() function - as is not recognized outside of it.

Move the class outside of main(), like so:

class Question  {
public:
    void askQuestion();
};

int main() 
{
    // you can use the Question class here, even though you haven't
    // defined all of its methods yet!
    Question q;
    q.askQuestion();
}

void Question::askQuestion() { }

... and this program does compile (godbolt.org).

That's not all, however... you're declaring your member variables (e.g. Question_text) inside each of your member functions. The local definition masks the class member, so you're only setting a local variable of your method, which gets destroyed when execution completes.


Other notes and suggestions:

  • No need to use the word Question again in a method name, if the class already has it. i.e. Question::ask() seems like a better choice of name than Question::askQuestion(). Same goes for Question::Question_text.
  • It's better to avoid using namespace std, and only using the classes, types or functions from std:: which you specifically intend to refer to.
  • If you think about it, your use of the Question class is rather artificial. Its code is mostly the code for giving the quiz, rather than of a question-as-such, a question-unto-itself. It seems like a better choice of "object" would be a set of answers-and-values, or question parameters. Setting the values can be done by constructing a QuestionParameters object, and asking the question could be a function that takes such an object.
  • If you have Answer_one, Answer_two, Answer_three - then you probably need a container, instead, e.g. std::vector<std::string> answers. You can then use an answer index instead of using if or switch statements.
einpoklum
  • 118,144
  • 57
  • 340
  • 684
0

Changes you must make to define the class outside of the main function Use the switch instead of if Use the int value instead of E to exit the program. I made changes to the code as follows

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

class Question
{
private:
    string Question_Text;
    string Answer_one;
    string Answer_two;
    string Answer_three;

    int Correct_Answer;
    int Question_Score;

public:
    void setValues(string, string, string, string, int, int);
    void askQuestion();
}; //end of class

//---------------------------
void Question ::askQuestion()
{
    string Question_Text;
    string Answer_one;
    string Answer_two;
    string Answer_three;

    int Correct_Answer;
    int Question_Score;
    int ans;
    int Total;

    cout << endl;
    cout << Question_Text << endl;
    cout << "1. " << Answer_one << endl;
    cout << "2. " << Answer_two << endl;
    cout << "3. " << Answer_three << endl
         << endl;
    cout << "Please enter your answer: " << endl;
    cin >> ans;

    if (ans == Correct_Answer)
    {
        cout << "That is correct!" << endl;
        Total = Total + Question_Score;
    }
    else
    {
        cout << "Sorry, that is incorrect" << endl;
        cout << "The correct answer was " << Correct_Answer << endl;
    }
} //end of askQuestion
//----------------------------------
void Question ::setValues(string q, string a1, string a2, string a3, int ca, int pa)
{
    string Question_Text;
    string Answer_one;
    string Answer_two;
    string Answer_three;

    int Correct_Answer;
    int Question_Score;

    Question_Text = q;
    Answer_one = a1;
    Answer_two = a2;
    Answer_three = a3;
    Correct_Answer = ca;
    Question_Score = pa;
} //end of setValues
//----------------------------------

int main()
{
    string username = "";
    int choice;
    char c;
    char answer;
    int x = 4;
    int y = 5;
    int z = x + y;
    int ans;
    int total;

    //welcome message
    cout << "Hello user, please enter your name:";
    cin >> username;
    cout << "Welcome to the programming tutorial " << username << "." << endl;

    //menu selection

    while (choice != 5)
    {
        cout << "What would you like to do? (Unit 1 - Declaring Variables (1), Unit 2 - Input/ Output (2), Unit 3 - Conditionals (3), Quizzes (4) or Exit (5))";
        cin >> choice;

        switch (choice)
        {
        case 1:
        {
            cout << "We will begin with defining variables. The first step to doing this is choosing which datatype your variable is.\n";
            cout << "The following are a few of the common datatypes used in programming.\n";
            cout << "Character ==> char\n";
            cout << "Integer ==> int, long, double\n";
            cout << "Boolean ==> bool\n";
            cout << endl;
            cout << "When declaring a variable, you must put its datatype before the variable name.\n";
            cout << "An example of this would be if we wanted to declare the value of x as 4.\n";
            cout << "We would write this as: \n";
            cout << "int x = 4\n";
            cout << "The program will now use the value 4 for the variable name 'x'\n";
            cout << endl;
            cout << "Now let's assume we assigned the value of 5 to the variable 'y'\n";
            cout << "If we wanted to add x and y and assign the sum to the variable 'z', we would write:\n";
            cout << "int z = x + y\n";
            cout << "Now when we use the variable 'z' in our program, it will perform the calculation given x=4 and y=5 and declare 9 as the value of the variable 'z'.\n";
            cout << "To test our code, we would write: " << endl;
            cout << "cout<<'x + y'<< z << endl; \n";
            cout << "If written correctly, it will display as: \n";
            cout << "x + y = " << z << "." << endl;
            break;
        }

        case 2:
        {
            cout << "Now that we understand the basics of declaring variables, let's discuss displaying, or output of, information to a user.\n";
            cout << "If you wanted to display a welcome message, for example, you would type:\n";
            cout << "cout << 'Welcome';\n";
            cout << "The line of code would start with 'cout' followed by two less than signs and then the message you wish to display in quotes.\n";
            cout << "Using this, you can ask the user for input.\n";
            cout << "Enter c to continue...";
            cin >> c;
            cout << "Let's say we have a program that flips a coin. You may want to ask the user how many times to flip the coin.\n";
            cout << "Assuming we previously declared this amount variable as 'int timesFlipped', we would 'cout' our question and the next line would read:\n";
            cout << "cin>> timesFlipped; \n";
            cout << "This will store the users input for the variable 'timesFlipped'\n";
            cout << "You almost always end a line of code with a semi colon." << endl;
            break;
        }
        case 3:
            cout << "This unit will cover conditional expressions." << endl;
            break;
        case 4:
        {
            string Question_Text;
            string Answer_one;
            string Answer_two;
            string Answer_three;

            int Correct_Answer;
            int Question_Score;
            Question q1;
            Question q2;
            Question q3;

            cout << username << ", you have chosen to take a quiz." << endl
                 << endl;
            int ans, score = 0;
            cout << "Unit One Quiz - Variables " << endl
                 << endl;

            q1.setValues("How would you declare the value of 'x' as 12? ",
                         "x=12()",
                         "x==12()",
                         "x=12;()",
                         3,
                         1);
            q2.setValues("What do you need to put before a variable when declaring it?",
                         "a name()",
                         "a value()",
                         "a datatype()",
                         3,
                         1);
            q3.setValues("Which data type would you use for a number that includes a decimal value?",
                         "int()",
                         "double()",
                         "float()",
                         2,
                         1);

            q1.askQuestion();
            q2.askQuestion();
            q3.askQuestion();
            cout << "Your score out of a possible 3 is " << total << endl;
            break;
        }

        case 5:
            cout << "Have a good day!";
            break;
        } //end of switch
    } //end of while

    system("pause");

    return 0;
} //end of main
M.A
  • 8
  • 1