if statement where array contains string

Apr 12, 2016 at 10:30pm
Write your question here.
Does anyone know how to check if a string array contains a string?
can i use an if ststement.
Thanks.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string order[10];

double total = 0.00;

for(int purchases = 0; purchases <= 1; purchases++)
{
cout << "Latte\t$2.50\n" << "Decaf\t$1.00\n" << "Mocha\t$3.00\n"
<< "Expresso$3.00\n";
cout << "What would you like to order?\n";
cin >> order[purchases];
}
for(int h = 0; h <= 1; h++)
{
if(latee == order[h]);
{
total = total + 2.50;
cout << "it works\n";
}
}
for(int i = 1; i <= 2; i++)
{
cout << order[i] << endl;
}
cout << "Your total is $" << total << endl;

return 0;
Last edited on Apr 13, 2016 at 1:36am
Apr 13, 2016 at 12:58am
edit: Oops, I misinterpreted the question.

http://www.cplusplus.com/reference/algorithm/find/
1
2
3
4
5
6
7
std::string haystack[5] = { /* . . . */ };
std::string needle{ /* . . . */ };
if( std::find( std::begin(haystack), std::end(haystack), needle ) != std::string::npos ) {
	/*
	. . .
	*/
}
Last edited on Apr 13, 2016 at 1:07am
Apr 13, 2016 at 1:00am
The most rudimentary way of doing this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <string>

int main() {

	constexpr int num_strings = 2;
	std::string strings[num_strings] = { "hello", "world" };
	//This is our array of strings.
	//It has two strings.

	std::string find_string = "world";
	//This is the string we're looking for.

	bool found = false;

	for (int i = 0; i < num_strings; ++i) {

		if (strings[i] == find_string) {
			found = true;
		}

	}

	if (found) {
		std::cout << "The string was found!" << std::endl;
	}
	else {
		std::cout << "The string wasn't found!" << std::endl;
	}

	return 0;
}


Note, that the for-loop doesn't terminate just because it's found the string we're looking for. All it does once our desired string is found is set found to true. If there were more string elements in our array, the for loop would continue searching the array, comparing elements against our find_string even though it was already found.
Topic archived. No new replies allowed.