Gabby
Gabby

Reputation: 41

Why is my array always giving a true answer?

My code here says that all values are true even if they aren't in the array. What am I doing wrong? For instance, I could input Chicago, and it will say "City found." I have tried to change the order around and change the "if(foundIt) to if(foundIt = true). It will still do the same.

// 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(int i = 0; i < NUM_CITIES; i++){
            if (x = i)
        foundIt = true;
      }


  // Write your test statement here to see if there is 
  // a match.  Set the flag to true if city is found. 
    if (foundIt)
      cout << "City found." << endl;
    else cout << "Not a city in Michigan." << endl; 





   // Test to see if city was not found to determine if 
   // "Not a city in Michigan" message should be printed. 


   return 0;  

} // End of main() 

Upvotes: 2

Views: 228

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

This loop

  for(int i = 0; i < NUM_CITIES; i++){
            if (x = i)
        foundIt = true;
      }

does not make sense. There is used an assignment in the if statement of the control variable i to the variable x.

if (x = i)

It seems you mean at least

  for(int i = 0; !foundIt && i < NUM_CITIES; i++){
            if ( inCity ==  citiesInMichigan[i] )
        foundIt = true;
      }

If you need the index of the found city then the loop can look like

size_t i = 0;

while ( i < NUM_CITIES && inCity !=  citiesInMichigan[i] ) i++;

if ( i != NUM_CITIES )
{
    // the city is found at position i
}
else
{
    // the sity is not found
}

Upvotes: 2

Related Questions