C ++测验:使用矢量正确循环显示答案选择

时间:2014-01-16 00:53:15

标签: c++ arrays c++11 vector

我需要我的程序将每个答案都与1)联系起来;但是,当我使用if语句使我的程序不能超过最高向量索引时,它会在第4个问题中重复值ab,并且值a对于第五个问题。

我希望输出看起来如何:

第一个问题: 1)a 2)b 3)c 4)d

第二个问题: 1)b 2)c 3)d 4)e

第三个问题: 1)c 2)d 3)e 4)a

第四个问题: 1)d 2)e 3)a 4)b

第五个问题: 1)e 2)a 3)b 4)c

实际输出:

第一个问题: 1)a 2)b 3)c 4)d

第二个问题: 1)b 2)c 3)d 4)a

第三个问题 1)c 2)a 3)b 4)c

第四个问题: 1)a 2)b 3)a 4)b

第五个问题: 1)a 2)a 3)a 4)a

如何修复代码以使输出看起来像我想要的那样?

#include <iostream>
#include <vector>
#include <string>
#include <array>
#include <cmath>
using namespace std;

int main()
{


    vector<string> vecQuestions = //vector that will hold all questions
    {
        "First Question: \n",
        "Second Question:\n",
        "Third Question\n",
        "Fourth Question: \n",
        "Fifth Question:\n"
    };
    vector<string> vecAnswers =   // the index of vecAnswers[] correlates to vecAnswers[] //holds all answers
    {
        "a",
        "b",
        "c",
        "d",
        "e"
    };

    array<int, 4> answer_choices = {{1,2,3,4}}; //sets answer choices
    for (unsigned int i =0; i<vecAnswers.size(); i++) //as long as there are questions
    {
        int answers_index = i;
        cout << vecQuestions[i];
        for (int x:answer_choices) // for all four values of array answer choices
        {
            int values_left = vecAnswers.size() - i-1;
            if (values_left < answers_index) //attempt to keep from accessing invalid memory from too large of vector size
            {
                 answers_index =0;
            }
            cout << x << ")" << vecAnswers[answers_index] << " ";
            answers_index++;
        }
        cout <<"\n\n";
    }

    return 0;
}

2 个答案:

答案 0 :(得分:2)

更简单的逻辑和更易读的代码。使用模块化% vecAnswers.size()

array<int, 4> answer_choices = {{1,2,3,4}}; //sets answer choices
for (unsigned int i =0; i<vecAnswers.size(); i++) //as long as there are questions
{
    int answers_index = i;
    cout << vecQuestions[i];
    for (int x:answer_choices) // for all four values of array answer choices
    {
        cout << x << ")" << vecAnswers[answers_index % vecAnswers.size() ] << " ";
        answers_index++;
    }
    cout <<"\n\n";
}

答案 1 :(得分:1)

我不清楚你想要这个代码做什么,但这些行看起来是一个问题:

int values_left = vecAnswers.size() - i-1;
if ( values_left < answers_index)
{
    answers_index =0; //--- ends up setting all values to 1
}

我相信你想要:

if (answers_index >= vecAnswers.size())
{
    answers_index =0; //--- ends up setting all values to 1
}

或更简洁:

answers_index %= vecAnswers.size();

否则它只是在内循环的后续迭代中不断重置answers_index,这就是你看到意外输出的原因。