Posted: . At: 12:08 PM. This was 4 years ago. Post ID: 14664
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.



Sponsored



A C++ example of how to search an array for certain words.


This program allows the user to search an array and then return any matches. Give the program two letters and it will search the array and try to find the matches.

compare.cpp
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
/*
	* Find an element in an array example. *
	* Type two characters and see if it matches *
	* an element in the array. *
*/
 
#include <stdio.h>
#include <string.h>
 
int main (int argc, char **argv) {
 
	int n;
	const char* x[] = {
		"Baron of Hell", "Demon", "Hellknight", "Cyberdemon",
		"Mancubus", "Revenant", "Heretic Imp", "Zombieman",
		"Sergeant", "Beholder", "Moloch", "Satyr", "Afrit",
		"Ettin", "Maulator", "Destroyer", "HereticImp",
		"Beserker", "Cacodemon", "PainElemental", "Archvile",
		"Korax", "Centaur","Menelkir","Traductus","Wendigo",
		"Heresiarch","Stalker", "Slaughtaur","Zedek"
	};
 
	printf ( "Type two characters to look for a certain monster:\n");
	for (n=0 ; n < sizeof(x) / sizeof(x[0]) ; n++) {
		if (strncmp (x[n],argv[1],2) == 0) {
			printf ("found %s\n",x[n]);
		}
	}
	return 0;
}

This is an example of the usage of this program.

┌─[jason@jason-desktop][~/Documents]
└──╼ $./robot He
Type two characters to look for a certain monster:
found Hellknight
found Heretic Imp
found HereticImp
found Heresiarch

This is a very useful programming tip. This is using strncmp. But this really does work very well. I recommend using Visual Studio Code for programming, it tells you if there are problems with your program or script.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.