Sequential Search for a string?

Hi there,

Last edited on
 
int searchList(string *, int, string *);


takes an array of string for its 3rd parameter.

You might want to slash off the square brackets.

Take note that indices should not be represented by a signed data type. For you situation, it is easy to monitor if you are going out of bounds. But in many cases, it is strongly recommended that you use size_type instead.

Here is a much cleaner, better and optimized code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
//I fail to see where you used fstream.h

//It is better to declare global constants this way.
#define ARRAY_SIZE 3

using namespace std;

//You do not actually need the second argument (int numElems) it is already a global.
int searchList(string array[], string value);

int main()
{
    string someArray[ARRAY_SIZE] = {"mouse", "cat", "ant"};
    int results = searchList(someArray, "ant");

    if (results == -1)
        cout << "You did not earn 100 points on any test"<<endl;
    else
    {
        cout << "You earned 100 points on test ";
        cout << (results + 1) << endl;
    }
    return 0;
}

int searchList(string array[], string value)
{    
    for(unsigned i = 0; i < ARRAY_SIZE; i++)
    {
        if(array[i] == value)
        {
            return i;
        }
    }
    return -1;
} 

Topic archived. No new replies allowed.