
Patrick B. answered 06/27/19
Math and computer tutor/teacher
using namespace std;
#include <stdio.h>
#include <iostream>
#include <string.h>
#define NUM_CITIES (16)
//removes leading and trailing white space characters from the string
TrimStr( char * str)
{
int iLength = strlen(str);
char * curPtr;
curPtr = &str[iLength-1]; //points at the last char before null terminator
//goes backwards looking for the first non-whitespace character
while ((*curPtr)==' '){ curPtr--; }
curPtr++; //goes forward one character and puts the null terminator, so trailing white spaces are gone
*curPtr='\0';
//points two pointers at the beginning
curPtr = &str[0];
char * basePtr = &str[0];
while ((*curPtr)==' '){ curPtr++; } //moves the current pointer to first non white-space character
while ((*curPtr )!= '\0') //while curPtr is NOT the null terminator, COPIES each char one at a time
{
*basePtr = *curPtr;
basePtr++; curPtr++;
}
*basePtr='\0'; //puts the null terminator
}
int main()
{
//* the array of city names in Michigan *//
char * MichiganCities[] = { "Ann Arbor",
"Detriot",
"Lansing",
"Battle Creek",
"Kalamazoo",
"Grand Rapids",
"South Lyon",
"Flint",
"Muskegon",
"Traverse City",
"Yipsilanti",
"Saginaw",
"Pontiac",
"Auburn Hills",
"Rogers City",
"Mt. Pleasant"};
char city_name[255];
//Prompts the user to input the name of the city and reads it into local variable
std::cout << "Please input the name of the city :>";
gets(city_name);
TrimStr(city_name);
//DEBUG: cout << ">" << city_name << "<" << endl;
int iFoundFlag=0; //assumes the city name is NOT in the array until proven that it is
int iLoop=0;
//linear searches the array for the city name
for (iLoop=0; iLoop<NUM_CITIES; iLoop++)
{
if (stricmp(city_name,MichiganCities[iLoop])==0) //string compare is NOT case sensitive
{
iFoundFlag=1; //there is a Match... the city name is found in the array
break; //escapes the loop
}
}
//Outputs the results of the search
if (iFoundFlag==1)
{
std::cout << city_name << " has been found : record # " << (iLoop+1) << endl;
}
else
{
std::cout << city_name << " is not a city in Michgan " << endl;
}
}