How to use an if statement to check if string exists in a specific array?

closed account (oN3h0pDG)
Hello, I need to know how to use an if statement to check if 2 string elements are in an array that contains 7 string elements for names. Also after that if they are in that array I have to swap those values. I'm not sure how to check, thanks for your help! :)

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

#include <iostream>
using namespace std;

void printArray(string names[]) {

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

		cout << names[i] << " ";

		}
}
int main() {
	int x = 0;
	string answer, name1, name2;
	string names[7] = {"John", "Dave", "Jim", "Amanda", "Kelsey", "Don", "Jennifer"};

	while (x < 1) {
	printArray(names);

	cout << endl << "Do you want to swap students? " << endl;
	cin >> answer;

	if (answer == "Yes" || answer == "yes") {

		cout << "Who would you like to swap?" << endl;
		cin >> name1;
		cin >> name2;

		if (name1 == /* ? */]) {

			// ?

		} else {

			cout << "No one of those names is not in line! Try again." << endl;

		}


	} else {

		cout << "Thanks, please behave now, students!" << endl;
		x++;
	}
	}

	return 0;

}
If it has to be a simplistic array like this then you would iterate through it with a for loop. Take the numberical constant that you have designating the size of your array and make it into a const unsigned Array_Size = 7; somewhere above Line 16. Use this to set the array size and also to designate the limit in your for loop. That way if you need to change it, you are only changing the constant in one place. You also need to save the position that the names were found at, so that's two more variables.

I just want to say that if you can get away with using any of the standard containers, this becomes much nicer looking in the end.
Topic archived. No new replies allowed.