looking for string

Hi, I would like to use this function to looking for some element from array of strings (JmenoSerialu).
This is what code blocks is writing
error: a function-definition is not allowed here before '{' token|

1
2
3
4
5
6
7
8
9
10
11
12
13
14
            void hledej(string JmenoSerialu[])
                {
                cout << "Zapis nazev hledaneho serialu" << endl;

                string x;
                cin >> x;
                int i;
                for (i=0, i<s.velikost, i++)
                    {
                if (x==JmenoSerialu[i])
                    {return JmenoSerialu[i]}
                return -1; //hledany prvek nenalezen
                }
        }
Last edited on
This makes more sense to me. sz is the size of the Jmen array ... and the return vale is the position in the array of the found item, or -1 if it isn't found.
(std:: is instead of writing using namespace std; )

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
#include <iostream>
#include <string>

int hledej(std::string JmenoSerialu[], size_t sz)
{
    std::cout << "Zapis nazev hledaneho serialu: ";
    
    std::string x;
    std::cin >> x;
    
    for (int i = 0; i < sz; i++)
    {
        if ( x == JmenoSerialu[i])
        {
            return i;
        }
    }
    return -1;
}


int main()
{
    std::string name[]{"Anna", "Bob", "Betty", "Bertha"};
    size_t size = sizeof(name)/sizeof(std::string);
    
    std::cout << "No of names: " << size << '\n';
    int which_name = hledej(name, size);
    
    if(which_name > 0)
        std::cout << name[which_name] << " was found\n";
    else
        std::cout << "Nobody by that name was found\n";
    return 0;
}
Last edited on
First off a void function cant have a return. That's probably the error.

Also you should not be returning -1 if the match isn't found in the for loop. That's basically just going to exit the loop if it's not found the first time through.

If it makes it out of the loop then it wasn't found at that point you could return a error value.

Also it appears that you are attempting to return either the string that was found or -1 hence 2 different return types you can only have 1 or the other.

I'd guess you could return a string="-1" or "false" or as demonstrated change the function return to int and return either the position of the string in the array or -1 if not found
Last edited on
you can return without a value, eg return;

but the error message to me is saying you have a function in a function. It didnt get to the return problem yet. You can't define a function within a function in c++.
Last edited on
Topic archived. No new replies allowed.