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.
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.