我想使用如下结构在c中制作带有多项选择题的程序:
struct exam
{
char quest[50];
char ans1[20];
char ans2[20];
char ans3[20];
int correct_answer;
};
struct exam question[3];/*number of multiple choices*/
我的代码有什么问题吗?
我不确定如何来填充结构。
答案 0 :(得分:3)
如果您的所有数据都是常量,您可以使用以下内容:
struct question {
const char *prompt;
const char *answers[3];
int correct_answer;
};
然后你可以设置一系列问题,如下:
const struct question questions[] = {
{ "Kernighan & who?", { "Ritchie", "Stroustrup", "Torvalds" }, 0 },
{ /* next question ... */
};
如果我这样做,我可能会在字符串中编码正确答案,即用'*'
或其他东西开始正确答案。当然,处理(打印和比较)答案的代码需要考虑到这一点。
答案 1 :(得分:0)
struct exam question[3];
以这种方式定义question
,这意味着你定义了3个元素的数组。数组中的每个元素都是exam
结构
它可以像这样填充:
strcpy(question[0].quest, "What's the name of The President?");
strcpy(question[0].ans1, "name 1");
strcpy(question[0].ans2, "name 2");
strcpy(question[0].ans3, "name 3");
question[0].correct_answer = 2;
strcpy(question[1].quest, "What's the surname of The President?");
strcpy(question[1].ans1, "surname 1");
strcpy(question[1].ans2, "surname 2");
strcpy(question[1].ans3, "surname 3");
question[1].correct_answer = 3;
你也可以用这种方式填写它:
struct exam question[3] = {
{"What's the name of The President?", "name 1", "name 2", "name 3",2}
{"What's the surname of The President?", "surname 1", "surname 2", "surname 3",3}
{"What's any thing?", "any thing 1", "any thing 2", "any thing 3",3}
}
答案 2 :(得分:0)
你的问题提到了C ++。你在C语言中的表现是可以的(除了答案应该是一个数组)。
但是这种实现在C ++中是不可接受的,因为有更好的方法:
struct question {
std::string prompt;
std::vector<std::string> answers;
int correct_answer;
};
也就是说,使用内置容器和字符串类。