【发布时间】:2015-09-16 03:13:35
【问题描述】:
我是 C++ 初学者,所以请像 5 岁一样跟我说话。
这是我想要做的:
将用户输入转换成字符串
userInput将
userInput和 2 个数组(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;
}
【问题讨论】:
-
永远不要在函数头中写
string answers[],因为它看起来像一个数组,但它实际上不是一个数组——它实际上与string *answers的含义相同。 (是的,标准委员会在做出决定时一定觉得自己特别脑残) -
@immibis 在第一个标准发布时,重要的是不要破坏太多现有代码,否则该标准不会被广泛采用。