【问题标题】:C++ Comparing vector elements to determine correct answerC ++比较向量元素以确定正确答案
【发布时间】:2015-02-19 00:24:40
【问题描述】:

我已经和这个斗争了一段时间。我正在尝试从 2 个向量创建分数结果,1 个向量是实际答案,另一个是输入的答案。 本质上比较:

for (i=1;i<=totalQ;i++){
cout<<"Enter question answer: ";
cin>>inputQ;
questions.push_back(inputQ);
}

到这里:

for (i=1;i<=totalQ;i++){
    cout<<"Enter your answer: ";
    cin>>studentA;
    answers.push_back(studentA);
    }

我无法弄清楚如何将元素相互比较以返回有多少相同(正确答案)。

最初我尝试不使用第二个向量,并通过这样做将来自第二个输入的字符串与问题向量进行比较:

for (i=1;i<=totalQ;i++){
    cout<<"Enter your answer: ";
    cin>>studentA;
       if(studentA == questions[i]){
          score=score+1}
    }

但是比较语句一直导致程序崩溃。经过一番研究后,我得出的结论是,我无法使用 [] 来比较向量,因此我决定创建一个向量来比较 2... 这还没有成功。

我如何比较这 2 个向量以提供匹配元素和索引的数量,或者我如何将输入与向量元素进行比较。

两个向量都是字符串向量,studentA 是字符串变量。

【问题讨论】:

  • 您的原始代码可能崩溃了,因为您一直使用基于 1 的索引,而questions[i],当i == totalQ 索引超出vector 的范围时。我不明白您在问什么...您有 N 个问题和 N 个答案,并且想将每个答案与一个问题相匹配?

标签: c++ vector string-comparison


【解决方案1】:

你可以这样做

#include <vector>
#include <iostream>
#include <string>
//#include <cstring>

using namespace std;

int main(int, char**)
{
    int i;
    int score = 0;
    int totalQ = 3;

    vector<string> questions;
    vector<string> answers;

    for (i=0;i<totalQ;i++)
    {
        string inputQ;
        cout<<"Enter question answer: ";
        cin>>inputQ;
        questions.push_back(inputQ);
    }

    for (i=0;i<totalQ;i++)
    {
        string studentA;
        cout<<"Enter your answer: ";
        cin>>studentA;
        answers.push_back(studentA);
    }

    for (i=0;i<totalQ;i++)
    {
        //if(strcmp(answers[i].c_str(), questions[i].c_str()) == 0)
        if(answers[i].compare(questions[i]) == 0)
        {
            score++;
        }
    }

    cout << "You got " << score<< " correct" << endl;
}

我假设您将答案存储为字符串。

你需要记住的事情是

  1. 要从 0 开始索引,这是在向量中使用运算符 [] 访问它们的方式。您不需要在循环中使用 &lt;=,它不会崩溃,因为您不会超出向量一个。
  2. 要在循环中比较字符串,您可以使用字符串的compare 方法或老式的strcmp

【讨论】:

  • 谢谢!我不得不调整一些东西,但是实现 compare 方法正是我想要的。我以前尝试过 strcmp 但它不适用于字符串。 IIRC 从读数来看仅限于 char 应用程序,不是吗?
  • @ErikKessel 你可以在注释掉的部分看到如何使用strcmp
【解决方案2】:

使用std::find函数,例如假设answers是正确答案的向量,answer是输入的答案:

if( std::find(answers.begin(), answers.end(), answer) != answers.end() ) {
      score+=1;
}

顺便说一句,您的程序崩溃了,因为您的索引从 1 开始并以 size 结束:

for (i=1;i<=totalQ;i++){

在 C++ 中向量索引从 0 开始,所以你应该是:

for (i=0;i<totalQ;i++){

【讨论】:

  • 我不认为 1 有什么不同,我使用它是因为 totalQ 是由用户定义的,所以我认为 1 而不是制作它 (i=0;i
【解决方案3】:

您的 for 循环没有遍历整个向量。索引从 0 开始,并使用

【讨论】:

    猜你喜欢
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2019-07-05
    • 1970-01-01
    相关资源
    最近更新 更多