【问题标题】:Array- looping through secondary array阵列-通过二级阵列循环
【发布时间】:2019-07-21 17:46:31
【问题描述】:

无法从第二个数组中获取索引以匹配第一个数组

// array constants 
const int people = 7;
const int phoneNumbers = 7;

int main() {
  char person, family; 
  int index; 
  string found;
  int size =7;

  //array declaration and set values
  string people [] ={"Darryl","Jasmine","Brian","Duane","Ayana","Mia","Maya"};

  // const char phoneNumbers  = 7;
  string phoneNumbers[] = {"678-281-7649", "818-933-1158", "212-898-2022", 
  "361-345-3782","817-399-3750","313-589-0460","818-634-4660"};

  //set boolean value
  found = "False";

  //initialize index 
  index = 0;

  // search variable and user input 
  cout << "who are you looking for?     " << endl;
  cin >> people[index];
  for (index=0; index<=6; index--) {
    if (people[index] == people[index] )
    cout << "phone num for " << people[index] << " is  "<< 
    phoneNumbers[index] << endl;
  }
  return 0;
}

当我放入 people[] 数组的 Jasmine 时,phoneNumbers[] 数组带回 phoneNumbers[] 的第一个索引,它应该带回 phoneNumbers[] 数组上的第二个索引

【问题讨论】:

  • 您对people[index] == people[index] 有何期待?永远正确。
  • 验证来自用户的输入是否与 people[index] 内容匹配。如何确保用户的输入与 people[index] 匹配,然后循环电话号码以匹配
  • //initialize index index = 0; - 为什么在声明 index 时不这样做??
  • cin &gt;&gt; people[index]; 您的用户输入会覆盖您的参考数据...
  • 我是学生,还在学习.. 你的意思是像这样初始化索引 - index = people[index]

标签: c++ arrays c++14


【解决方案1】:

这里有两个问题。

  • 您将 people[0] 的内容替换为 cin - 因此数组的第一项将始终是用户的输入。

  • 您是递减索引,因此 FOR 循环转到索引 0、-1、-2...这是问题,因为 C 和 C++ 中的数组从 0 变为上限值。

我希望添加一个变量:

string input;

然后:

cin >> input;

应该使用for循环:

for (index = 0; index < 6; index++)

在你的情况下我会使用:

if (person[index] == input) ...

【讨论】:

  • 格式化您的帖子。提交前看一下。当您不确定如何操作时,发布界面上会提供帮助选项和信息。慢慢来。做对了。
【解决方案2】:

更简洁的方法是使用 C++ 标准模板库提供的std::map。以下是我对您要实现的目标的看法:

// phoneNumber.cpp
#include <iostream>
#include <map>

int main()
{   
    // delcare a map variable that maps people's names to phone numbers
    std::map <std::string,std::string> lookUpPhoneNumber = {
        {"Darryl", "678-281-7649"},
        {"Jasmine", "818-933-1158"},
        {"Brian", "212-898-2022"},
        {"Duane", "361-345-3782"},
        {"Ayana", "817-399-3750"},
        {"Mia", "313-589-0460"},
        {"Maya", "818-634-4660"}
    };

    // take input name
    std::string inputName;
    // user prompt
    std::cout << "who are you looking for?: ";
    std::cin >> inputName;

    // look up name in map
    if(lookUpPhoneNumber.find(inputName) != lookUpPhoneNumber.end()){
        std::cout << "Phone num for " << inputName << " is: " << lookUpPhoneNumber[inputName] << "\n";
    } else{
        std::cout << "Name does not exist!\n";
    }

    return 0;
}   

要编译和运行,请使用以下命令:

g++ -std=c++11 -o phoneNumber phoneNumber.cpp
./phoneNumber

或者检查您的编译器选项以启用使用c++11 标准或更高版本进行编译。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多