0

I am currently working on a program and I was wondering if there was anyway to input an element FROM an array and find an element in the same location of a parallel array.

string names[3]={"Jim", "John", "Jeff"};
int num[3]={1,2,3};
cout<<"Enter either Jim, John, or Jeff"<<endl;
cin<<name;

If I were to input the name 'John' how would I get the output to print out something along the lines of: 'John has the number 2'

6502
  • 112,025
  • 15
  • 165
  • 265
  • Take a look at this to find the index of the value: http://stackoverflow.com/questions/3909784/how-do-i-find-a-particular-value-in-an-array-and-return-its-index. Once you have the index it's trivial to retrieve the value in another array at the same index. – sunny Aug 01 '15 at 06:00
  • Take a look at http://www.thegeekstuff.com/2013/01/c-argc-argv/, it may help you – aLoneStrider Aug 01 '15 at 06:14

3 Answers3

2

Write a loop

for (int i = 0 i < 3; ++i)
{
    if (name == names[i])
    {
      cout << name " has the number " << num[i] << "\n";
      break;
    }
}
john
  • 85,011
  • 4
  • 57
  • 81
2

Unless you're truly required to use parallel arrays, you might want to consider an std::map or std::unordered_map, which are designed for precisely this sort of problem:

std::map<std::string, int> people{
    { "Jim", 1 },
    { "John", 2 },
    { "Jeff", 3 }
};

std::cout << "Please enter a name: ";
std::string name;
std::cin >> name;

auto pos = people.find(name);
if (pos != people.end())
    std::cout << name << " has the number: " << pos->second;
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

C++ doesn't provide that for arrays, but you can use std::find from the <algorithm> library that can work using two iterators.

Iterators are generalizations of pointers and you can use that algorithm also using pointers; an example of the this method is:

string *s = std::find(names, names+3, name);
int index = s - names; // 0, 1 or 2; if not present it will be 3
6502
  • 112,025
  • 15
  • 165
  • 265