Reputation: 77
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'
Upvotes: 0
Views: 102
Reputation: 490178
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;
Upvotes: 2
Reputation: 114539
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
Upvotes: 0
Reputation: 87957
Write a loop
for (int i = 0 i < 3; ++i)
{
if (name == names[i])
{
cout << name " has the number " << num[i] << "\n";
break;
}
}
Upvotes: 2