/***************************************************** * Program to demonstrate the use of searching * * subroutines of unit FSearch. * * -------------------------------------------------- * * SAMPLE RUN: * * (An ordered list of 16 names is given in text file * * 'search.dat'). * * * * # of items in list = 16 * * What name would you like to look for? David * * Linear serach for (f)irst, (a)ll, or (b)inary? f * * David found at position 5. * * Try again (y/n)? y * * What name would you like to look for? Grace * * Linear serach for (f)irst, (a)ll, or (b)inary? a * * Grace at position 9. * * Grace at position 10. * * Grace at position 11. * * 3 occurence(s) found. * * Try again (y/n)? y * * What name would you like to look for? Grace * * Linear serach for (f)irst, (a)ll, or (b)inary? b * * Grace found at position 10. * * Try again (y/n)? n * * * * -------------------------------------------------- * * Ref.: "Problem Solving with Fortran 90, By David R.* * Brooks, Springer Verlag, 1997". * * * * C++ Release By J-P Moreau, Paris. * * (www.jpmoreau.fr) * ****************************************************** To link with fsearch.cpp ------------------------ */ #include #include #include typedef char Str20[21]; //Names of length 20 extern Str20 a[], target; //see fsearch.cpp char YesNo[2], choice[2]; int size, where, how_many; void GetList() { FILE *fp; fp=fopen("search.dat","r"); size=0; while (!feof(fp)) { fscanf(fp, "%s", a[size]); size++; } size--; fclose(fp); printf("\n # of items in list = %d\n", size); } //functions implemented in fsearch.cpp void FindFirst(int, int *); void FindAll(int, int *); void Binary(int, int, int *); void main() { GetList(); // read names from input file strcpy(YesNo,"y"); while (YesNo[0]=='y') { printf(" What name would you like to look for? "); scanf("%s", target); printf(" Linear serach for (f)irst, (a)ll, or (b)inary? "); scanf("%s",choice); switch(choice[0]) { case 'a': FindAll(size, &how_many); if (how_many>0) printf(" %d occurence(s) found.\n", how_many); else printf(" %s not found.\n", target); break; case 'b': Binary(0,size-1, &where); if (where>0) printf(" %s found at position %d.\n", target, where); else printf(" %s not found.\n", target); break; case 'f': FindFirst(size, &where); if (where>0) printf(" %s found at position %d.\n", target, where); else printf(" %s not found.\n", target); } printf(" Try again (y/n)? "); scanf("%s", YesNo); } } // end of file search.cpp