2

So i want to make a quiz program with structs. I have the question, options and the answer in a struct. But i have multiple questions(structs) so i wrote a function to nicely format the input and output. But seems like it doesn't work because i can't use variable struct in functions.

Here's the code:

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


struct q0{
    string question = "Which sea animal has a horn?";
    string arr[3] = {"Dolphin", "Clownfish", "Narwhal"};
    int correctAnswer = 3;
};

struct q1{
    string question = "What is the biggest animal in the world?";
    string arr[3] = {"Blue Whale", "Elephant", "Great White Shark"};
    int correctAnswer = 1;
};

void quiz(struct q){
    cout<<q.question<<endl;
    for(int i = 0; i<3; i++){
        cout<<i+1<<". "<<q.arr[i]<<endl;
    }
    int answer;
    cin>>answer;
    (answer == q.correctAnswer) ? cout<<"Correct\n"<<endl : cout<<"Inorrect\n"<<endl;
}

int main(){
    quiz(q0);
    quiz(q1);
}
Jason
  • 36,170
  • 5
  • 26
  • 60
  • 8
    you somewhat misunderstood the purpose of custom data types. You do not need 1 class per question, but rather one class `Question` and then several instances of that class. I suggest you this https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – 463035818_is_not_an_ai Jul 19 '22 at 08:14
  • 1
    Don't know why this question gets down votes. It's a good example of a newbie asking the wrong question (how do I use multiple structs in a function) but because they included the code the real solution to the problem is obvious. This is a well asked question, +1 from me. – john Jul 19 '22 at 08:40

1 Answers1

4

You don't need to create a separate class-type for each question when you can create a single Question class with appropriate data members and then pass instances of that Question class to the function quiz as shown below:

//class representing a single question
struct Question{
    std::string question;
    std::string arr[3];
    int correctAnswer;
};

void quiz(const Question& q){
    std::cout<<q.question<<std::endl;
    for(int i = 0; i<3; i++){
        std::cout<<i+1<<". "<<q.arr[i]<<std::endl;
    }
    int answer;
    std::cin>>answer;
    (answer == q.correctAnswer) ? std::cout<<"Correct\n"<<std::endl : std::cout<<"Inorrect\n"<<std::endl;
}

int main(){
    //create object 1 of type Question
    Question obj1{"What is the biggest animal in the world?", {"Dolphin", "Clownfish", "Narwhal"}, 3};
    //pass obj1 to function
    quiz(obj1);
    //create object 2 of type Question
    Question obj2{"What is the biggest animal in the world?", {"Blue Whale", "Elephant", "Great White Shark"}, 1};
    //pass obj2 to function
    quiz(obj2);
}

Working Demo

Jason
  • 36,170
  • 5
  • 26
  • 60