数组 - 循环遍历辅助阵列

Array- looping through secondary array

本文关键字:阵列 遍历 循环 数组      更新时间:2023-10-16

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

// 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;
}

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

这里有两个问题。

  • 你正在用 cin 替换 people[0] 的内容 - 所以数组的第一项将始终是用户的输入。

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

我更愿意添加一个变量:

string input;

然后:

cin >> input;

对于循环应使用:

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

在您的条件下,我会使用:

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

一个更简洁的方法就是使用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标准或更高版本的编译。