为什么我的数组总是给出一个真实的答案



我在这里的代码说,所有值都是true,即使它们不在数组中。我做错了什么?例如,我可以输入Chicago,它会说"City found"。我已经尝试更改订单,并将"if(foundIt("更改为if(found it=true(。它仍然会这样做。

// 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() 

此循环

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

没有道理。在控制变量i的if语句中使用了变量x的赋值。

if (x = i)

你的意思似乎至少是

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

如果你需要找到的城市的索引,那么循环可以看起来像

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
}

相关内容