Home > database >  Using multiple structs in a function c
Using multiple structs in a function c

Time:07-19

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);
}

CodePudding user response:

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

  • Related