第一部分
你绝对可以使用Excel编辑您的问题,并进行保存。但是,当您保存它时,请注意文件格式。
要将Excel文件保存为.csv
文件而不是.xls
或.xlsx
文件。只需转到文件 - >另存文件为 - >并将类型更改为.csv
。
这是因为,阅读.csv
文件是一个容易得多。 .csv
文件具有在由逗号(,
),并且每个行由一个新行('\n'
)字符分隔行的每个小区。
所以,这里是一个样本Excel文件:
后,我将它保存为.csv
文件,并使用文本编辑器(凌动,这里)打开它,它看起来是这样的:
之后,你只需要编写一些代码来读取文件。
这是我使用的代码(我已经添加了过多的评论使代码更清晰,适合初学者):
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;
const int MAX_QUESTIONS = 3;
const int COLUMNS = 6; //Question, Options A, B, C, D, Correct Answer
int main() {
ifstream fp;
fp.open("test.csv");
//If file could not be opened
if (fp.fail()) {
std::cout << "failed to open file" << std::endl;
return 1;
}
//Create a 2D vector of strings to store the values in the file
vector< vector<string> > table;
string line;
//Loop through the entire file (fp)
//Store all values found until I hit a newline character ('\n') in the string line
//This loop automatically exits when the end-of-file is encountered
while (getline(fp, line, '\n')) {
//Create an temporary vector of strings to simulate a row in the excel file
vector<string> row;
//Now I am passing in this string into a string stream to further parse it
stringstream ss;
ss << line;
string part;
//Similar to the outer loop, I am storing each value until I hit a comma into the string part
while (getline(ss, part, ',')) {
//Add this to the row
row.push_back(part);
}
//Add this row to the table
table.push_back(row);
}
//Print out the entire table to make sure your values are right
for (int i = 0; i <= MAX_QUESTIONS; ++i) {
for (int j = 0; j < COLUMNS; ++j) {
cout << table[i][j] << " ";
}
cout << endl;
}
return 0;
}
第二部分
要选择一个随机数,你可以使用这个代码(我借它another answer)
#include <random>
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(min,max); // guaranteed unbiased
auto random_integer = uni(rng);
不像old method,这不会对低端创建偏差。但是,新引擎仅在C++ 11编译器中可用。所以记住这一点。如果您需要使用旧方法,您可以按照此answer纠正偏差。
要选择5个不同的数字,每次生成一个随机数字时,将它存储在一个数组中,并检查这个数字是否已被使用。这可以防止重复问题。
最简单的数据将是从文本文件加载数据,一个如果您需要获取随机记录,则应该使用支持按数字索引的数据结构,希望有帮助 –