Array search

I need to be able to take a input file like
4
Brianna
Paul
Lindsey
Lisa
and search Li and find Lindsey and Lisa
Right now I can only find the element if the full string is entered. How can I search the array with only a piece of the array entered?
Also I have to use arrays I can not use vectors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void search(ifstream& infile){
int number;
infile>>number;
string firstname1[number],lastname2[number],birthdate3[number];

for(int i=0; i<number; i++){
    infile>>firstname1[i]>>lastname2[i]>>birthdate3[i];

}
string itemToFind;
cout<<"Name?"<<endl;
cin>> itemToFind;
for(int i = 0; i < number; i++){
     if(firstname1[i] == itemToFind){
         cout<<firstname1[i];
     }
}


}
Last edited on
You can look for prefixes by, instead of using ==, use the find() method of the std::string class to find substrings and check to make sure it appears at the beginning of the string.
1
2
infile>>number;
string firstname1[number]
This is invalid C++. VLA arrays are not allowed by C++ Standard. Some compiles might allow them, but it highly unportable and there is great possibility that it will not compile on other machines.
How can I search the array with only a piece of the array entered?
DO you need only matches from the beginning of string, e.g. in array {Lisa, Colibri} search by "Li" will find only "Lisa"? Should it be case sensitive?

Anyway, i suggest you to look at the string::find() member function: http://en.cppreference.com/w/cpp/string/basic_string/find
What do you mean? How can I fix it then?
Here's one way to do what you're asking:

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
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <vector>
#include <algorithm>

std::vector<std::string> extractTokens(std::istream& is)
{
    std::vector<std::string> tokens;
    std::string token;

    while (is >> token)
        tokens.push_back(token);

    return tokens;
}

int main()
{
    std::istringstream is
    {
        "Brianna\n"
        "Lindsey\n"
        "Paul\n"
        "Lisa\n"
    };

    auto names = extractTokens(is);
    std::sort(names.begin(), names.end());


    std::vector<std::string> patterns = { "Li", "Br", "Lin", "P", "Zi", "Au", "i" };

    for (auto& pattern : patterns)
    {
        auto it = std::lower_bound(names.begin(), names.end(), pattern);

        std::cout << "Results for \"" << pattern << "\" are:\n";

        if (it != names.end() && it->find(pattern) == 0)
        {
            while (it != names.end() && it->find(pattern) == 0)
                std::cout << '\t' << *it++ << '\n';
        }
        else
            std::cout << "\tNo results.\n";
        std::cout << '\n';
    }
}


http://ideone.com/0jZfm9
Topic archived. No new replies allowed.