如何将两个数组(字符串)传递给一个函数,并与一个字符串进行比较

C++ How to pass 2 arrays (of strings) to a function, and compare to a string

本文关键字:字符串 一个 函数 比较 两个 数组      更新时间:2023-10-16

我是一个c++初学者,所以像我5岁一样和我说话。

我要做的是:

  • 将用户输入转化为字符串userInput

  • userInput和两个数组(answersoutcomes)传递到函数answerCheck

  • 比较userInputanswers数组

  • 如果有匹配,从outcomes

  • 输出字符串
  • 如果没有匹配,循环,请求userInput

我用answersSize输出answers的大小。它输出1而不是预期的2。

我不知道如何将数组中的信息传递给answerCheck函数。

有什么建议吗?

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int question1();
bool answerCheck(string[], string[], string);
int main() {
    question1();
    system("pause");
    return 0;
}
int question1() {
    cout << "Do you want to go LEFT or RIGHT?" << endl;
    string answers[2] = { "left", "right" }; 
    string outcomes[2] = { "you went left", "you went right" }; 
    string userInput = ""; 
    getline(cin, userInput);
    // outputs correct size of answers array for testing ======
    int answersSize = sizeof(answers) / sizeof(string); 
    cout << "Correct size of answers: "<< answersSize << endl;
    // ========================================================
    answerCheck(answers, outcomes, userInput);
    return 0;
}

bool answerCheck(string answers[], string outcomes[], string userInput){ 
    int answersSize = sizeof(answers) / sizeof(string); 
    cout << "Size of answers: "<< answersSize << endl;
    for(int i=0; i < answersSize; i++){ 
        if(userInput.find(answers[i]) != string::npos){
            cout <<"n" << outcomes[i] <<"n" << endl;
            return true;
        }
    }
    cout << "Try putting in something else." << endl;
    return false;
}

问题就在这里:

int answersSize = sizeof(answers) / sizeof(string); 

如果你把它打印出来,你会发现sizeof(answers)是指针的大小(4或8字节),而不是整个数组的大小。您需要将数组大小作为函数参数传入,或者使用像std::vector这样的类类型,以更c++的方式封装它。

对于初学者的一般建议是使用像std::vector这样的c++类而不是普通的C数组。在你的例子中,不是

string answers[2] = { "left", "right" }; 
使用

std::vector<std::string> answers{ "left", "right" };

和声明函数

bool answerCheck(std::vector<string> const& answers, 
                 std::vector<string> const&outcomes, 
                 string const& userInput)

如果你正在读一本介绍性的书,它首先介绍了c风格的代码,我会把它扔掉。一个很好的c++入门网站是https://isocpp.org/tour.

相关文章: