0

次のような構造を使用して、多肢選択式の質問を含むプログラムを 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*/

私のコードに何か問題がありますか?

構造を埋める方法がわかりません。

4

3 に答える 3

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 ... */
};

もし私がこれを行うとしたら、おそらく正しい答えを文字列にエンコードするでしょう。つまり、正しい答えを'*'何かで始めます。もちろん、回答を処理 (印刷して比較) するコードでは、それを考慮する必要があります。

于 2013-01-16T14:47:51.007 に答える
0
struct exam question[3];

defining question in this way, that means your are defining array of 3 elements. each element in the array is an exam structure

And it could be filled like this:

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;

And you can fill it in this way too:

  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}
  }
于 2013-01-16T14:45:19.893 に答える
0

あなたの質問はC++に言及しています。あなたのやり方はCでOKです(答えが配列でなければならないという事実を除いて)。

しかし、この実装は C++ では受け入れられません。より良い方法があるからです。

struct question {
    std::string prompt;
    std::vector<std::string> answers;
    int correct_answer;
};

つまり、組み込みのコンテナーと文字列クラスを使用します。

于 2013-01-16T14:50:13.363 に答える