How do I use flag variables to produce output for a program designed to search an array for a string provided via user input?

Viewed 461

I'm working on an ungraded practice assignment and am struggling with the C++ code required. The assignment parameters are to write a program which takes a string provided by user input, searches an array containing 10 elements, and sets the value of a flag variable depending on whether or not user input matches a string contained within the array. The program then outputs a phrase if the string was not found, as determined by referencing the value of the flag variable.

I have the following code so far:

// MichiganCities.cpp - This program prints a message for invalid cities in Michigan.  
// Input:  Interactive
// Output:  Error message or nothing

#include <iostream>
#include <string>
using namespace std;

int main() 
{
   // Declare variables
   string inCity;     // name of city to look up in array
   const int NUM_CITIES = 10;
   // Initialized array of cities
   string citiesInMichigan[] = {"Acme", "Albion", "Detroit", "Watervliet", "Coloma", "Saginaw", "Richland", "Glenn", "Midland", "Brooklyn"}; 
   bool foundIt = false;  // Flag variable
   int x;             // Loop control variable

   // Get user input
   cout << "Enter name of city: ";
   cin >> inCity; 
    
   // Write your loop here  
   for(x=0; x<NUM_CITIES; x++){
      // Write your test statement here to see if there is 
      // a match.  Set the flag to true if city is found. 
     if(citiesInMichigan[x] == inCity)[
       set foundIt = true,;
       break;
     ]
 }
            
   // Test to see if city was not found to determine if 
   // "Not a city in Michigan" message should be printed. 
if(foundIt == false){
  cout << "City not in Michigan.";
  return 0;
}

} // End of main() 

I'm fairly certain what I've got here should do what I'm trying to do, but I get syntax errors requesting brackets [] in odd places and I'm lost on what I'm doing wrong.

I'm not looking for someone to provide correct code for me to simply copy, as I'm trying to learn. I'm looking for someone who can explain what I've done wrong, what rules I'm breaking, and/or what steps I can take to get this code working.

1 Answers

You have the right idea, but have a couple of syntactic mistakes.

First, blocks in C++ (and many other languages), are denoted by curly braces ({ and }), not square brackets like you have in your condition.
Second, setting a value to a variable is done by the assignment operator, = (i.e., somevariable = somevalue). There is no "set" keyword in C++.

To put those two points together, the condition inside the loop should look like this:

if (citiesInMichigan[x] == inCity) {
    foundIt = true;
    break;
}
Related