首页 > 解决方案 > 如何使用标志变量为旨在搜索数组以查找通过用户输入提供的字符串的程序生成输出?

问题描述

我正在处理一项未评分的练习作业,并且正在努力处理所需的 C++ 代码。赋值参数是编写一个程序,该程序接受用户输入提供的字符串,搜索包含 10 个元素的数组,并根据用户输入是否与数组中包含的字符串匹配来设置标志变量的值。如果没有找到该字符串,则程序会输出一个短语,这通过引用标志变量的值来确定。

到目前为止,我有以下代码:

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

我相当确定我在这里所得到的应该做我想做的事情,但是我在奇怪的地方收到了请求括号 [] 的语法错误,而且我对自己做错了什么感到迷茫。

我不是在寻找有人为我提供正确的代码来简单地复制,因为我正在努力学习。我正在寻找能够解释我做错了什么、我违反了哪些规则和/或我可以采取哪些步骤来让这段代码正常工作的人。

标签: c++arraysloopssyntaxflags

解决方案


你有正确的想法,但有几个语法错误。

首先,C++(和许多其他语言)中的块用大括号 ({}) 表示,而不是像你在你的情况下那样的方括号。
其次,为变量设置值是由赋值运算符完成的,=(即somevariable = somevalue)。C++ 中没有“set”关键字。

要将这两点放在一起,循环内的条件应如下所示:

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

推荐阅读