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

标签 c++ arrays function

<分区>

我是 C++ 初学者,所以跟我说话就像我才 5 岁一样。

这是我正在尝试做的事情:

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

  • userInput 连同 2 个数组(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++ 的方式封装它。

关于C++ 如何将 2 个数组(字符串)传递给一个函数,并与一个字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32599157/

相关文章:

python - 如何拆分数组,然后在 0 和第 N 个值之间追加数组,然后在下一组中重复相同的步骤?

c - 试图让这个显示功能起作用

javascript - React 将组件作为参数传递给函数

c++ - 当我尝试使用特定路径打开文件时出现错误

c# - 托管 C++ 中的 List<Tuple<int, float>>

c++ - std::list - 对一项进行排序

java - 如何从 ArrayList<ArrayList<String[]> 获取元素?

c++ - 不可变全局对象应该声明为 'const my_result_t BLAH;' 还是 'extern const my_result_t BLAH;' ?

javascript - 数组中的未定义条目在使用 `true` 将它们解析为 boolean 值后返回 `every`

python - 如何在python中不指定默认参数?