I wrote a code which shows a question and 4 answers, ask to choose the correct one, and checks the choice. Now I would build a table which would contain 6 columns: question/a/b/c/d/correct_answer, and about hundred of lines with my questions. Now I would like my program to randomly choose 5 of a question from table and show it to user.
First question is, can I do my table in Excel and use it than in Visual Studio? If not, what software should I use to do table like this as simply as possible, and how to implement it into my Visual studio project? If yes, how to implement Excel table to my Visual studio project?
Second question is, what simplest code should I write to randomly choose 5 of 100 question from my table?
A code of a question is:
int main()
{
string ans; //Users input
string cans; //Correct answer, comes from table
string quest; //Question, comes from table
string a; // Answers, come from table
string b;
string c;
string d;
int points; //Amount of points
points = 0;
cout << "\n" << quest << "\n" << a << "\n" << b << "\n" << c << "\n" << d << "\n";
cout << "Your answer is: ";
cin >> ans;
if (ans == cans)
{
points = points + 1;
cout << "Yes, it is correct\n";
}
else
{
cout << "No, correct answer is " << cans << "\n";
}
return 0;
}
First Part
You can definitely use Excel to edit your questions and save them. But when you save it, pay attention to the file format.
You want to save your Excel file as a
.csv
file instead of.xls
or.xlsx
file. Just go to File -> Save File As -> and change type to.csv
.This is because, reading
.csv
files is a lot easier..csv
files have each cell in row separated by a comma (,
) and each row by a newline ('\n'
) character.So, here is a sample Excel file:
After I save it as a
.csv
file and open it using a text editor (Atom, here), it looks like this:After, that you only need to write some code to read the file.
This is the code I used (I've added excessive comments to make the code more explicit for beginners):
Second Part
To choose a random number, you can use this code (I borrowed it from another answer)
Unlike the old method, this doesn't create bias towards the lower end. However, the new engine is available only in C++11 compilers. So keep that in mind. If you need to use the old method, you can correct the bias by following this answer.
To choose 5 different numbers, each time you generate a random number store it in an array and check whether this number has already been used. This can prevent repetition of questions.