如何将两个数组(字符串)传递给一个函数,并与一个字符串进行比较
C++ How to pass 2 arrays (of strings) to a function, and compare to a string
我是一个c++初学者,所以像我5岁一样和我说话。
我要做的是:
-
将用户输入转化为字符串
userInput
-
将
userInput
和两个数组(answers
和outcomes
)传递到函数answerCheck
-
比较
userInput
和answers
数组 -
如果有匹配,从
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.