user836910
user836910

Reputation: 484

trying to perform an index search for string

im trying to write a code that should allow me to search a string of array that i enter when prompt. the program ask the uses to enter certain amount or data and then asks the use to perform a search. im having a hard time search for the input. i can do this with integers but now string please help. how would you do this.

#include <iostream>

using namespace std;

void contactArray(string a[], int size);

string search(const string a[], int size, string find);

int main( )
{
    cout << "This program searches a list .\n";
    const int arraySize = 3;
    string a[arraySize];

    contactArray(a, arraySize);

    string find;
    cout << "Enter a value to search for: ";
    cin >> find;
    string lookup = search(a, arraySize, find);
    if (lookup == " ")
        cout << find << " is not in the array.\n";
    else
        cout << find << " is element " << lookup << " in the array.\n";
    return 0;
}

void contactArray(string a[], int size)
{
    cout << "Enter " << size << " list.\n";
    for (int index = 0; index < size; index++)
        cin >> a[index];
}

int search(const string a[], int size, string find)
{
    string index = "";
    while ((a[index[3]] != find) && (index < size))
        cout<<"try again"<<endl;
    if (index == find)        
        index = "";
    return index;
    cout<<"hgi";
}

Upvotes: 0

Views: 947

Answers (3)

Sandoichi
Sandoichi

Reputation: 254

instead of

int search(const string a[], int size, string find)
{
    string index = "";
    while ((a[index[3]] != find) && (index < size))
        cout<<"try again"<<endl;
    if (index == find)        
        index = "";
    return index;
    cout<<"hgi";
}

try something like

int search(string a[], int size, string find)
{
      int index = -1;
      for(int i=0;i<size;i++)
      {
         if(a[i] == find)
         {
             index = i;
             break;
         }
      }
      return index; 
}

If the function returns -1, the string wasn't found. Any other return is the place in the array where the 'find' string is located.

Upvotes: 1

Mooing Duck
Mooing Duck

Reputation: 66932

You can do it with integers? Do it with integers, call that function with strings, and wherever you get a cannot convert string to int compiler error, change the word int to string. It should be almost exactly the same.

Upvotes: 1

jakx
jakx

Reputation: 758

Use a for loop to iterate through the array and check if the value is in the array. There is probably a C++ function to do this cstdlib and I know that .Net has this built in.

Upvotes: 0

Related Questions