Finding a match between player input string and string array elements?

Backstory:

Hello guys! I'm new to this forum and just started coding in c++ this Monday. As my first test program I decided to make a simple text adventure game. The computer outputs some text and the player can answer several things to make the story progress in different ways.

Problem:

It's been going along nicely, but I soon realized that for simple answers like yes or no I had to repeat way too much code. So I decided I should make a function that automatically checks if the answer matches with any in my string array that holds "yes" answers, and if it doesn't it will then check my other array that holds "no" answers.

When I try to compile my project though, I get a bunch of errors about how I can't use "==" in this case. Can anybody help me get this to work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int checkAnswer(string playerInput) {

	string answerArrayYes[6] = {"yes","Yes","YES","sure","Sure","SURE"};
	string answerArrayNo[3] = {"no","No","NO"};

	int amountOfYesAnswers = sizeof(answerArrayYes) / sizeof(answerArrayYes[0]);
	int amountOfNoAnswers = sizeof(answerArrayNo) / sizeof(answerArrayYes[0]);

	for (int i = 0; i < amountOfYesAnswers; i++) {
		if (playerInput == playerInput.find(answerArrayYes[i])){
			cout << "Yay" << endl;
			return 1;
		} 
	}
	for (int i = 0; i < amountOfNoAnswers; i++) {
		if (playerInput == playerInput.find(answerArrayNo[i])){
			cout << "Boo" << endl;
			return 2;
		}
	}
	cout << "Check finished" << endl;
	return 0;
};
Last edited on
std::string::find returns the position where the string was found. If the string was not found it returns std::string::npos. If it doesn't return std::string::npos it means that the the word was found.
if (playerInput.find(answerArrayYes[i]) != std::string::npos){

Last edited on
Thanks so much for responding so quickly! I entered what you said and it worked perfectly! May I just ask what npos means so I know when to use it in the future?
The return type of std::string::find is std::size_t. std::string::npos is a constant of type std::size_t having the biggest value that std::size_t can have. I think npos stands for "No Position".
Last edited on
Topic archived. No new replies allowed.