c++ - 如何使用标志变量为旨在搜索数组以查找通过用户输入提供的字符串的程序生成输出?
问题描述
我正在处理一项未评分的练习作业,并且正在努力处理所需的 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++(和许多其他语言)中的块用大括号 ({
和}
) 表示,而不是像你在你的情况下那样的方括号。
其次,为变量设置值是由赋值运算符完成的,=
(即somevariable = somevalue
)。C++ 中没有“set”关键字。
要将这两点放在一起,循环内的条件应如下所示:
if (citiesInMichigan[x] == inCity) {
foundIt = true;
break;
}
推荐阅读
- java - spark中读取数据库的执行时间
- ios - 键盘向上滑动时将 UIView 固定到屏幕顶部
- c++ - 模板的静态成员变量是定义的还是专门的?
- swift - SwiftUI - 无法呈现 jsonData
- mqtt - Paho MQTT 客户端缓存消息在 Mosquitto 服务器上的意外行为
- php - 如何在 Laravel 中查询两个表
- dart - Dart Map 排序 - 基于列表的值
- ruby - 拦截输出到 STDERR
- sql - SQL 将三列合二为一
- javascript - 当我尝试 forEach() "Function returned undefined, expected Promise or value" "时,Firebase Cloud Function 给出错误