-3

I have a c++ program which opens an url depending in what the user inputs.

Here's the code:

#include <iostream>
#include <string>
using namespace std;

int main(){
    int i = 1;
    string google = "https://www.google.com/search?q=";
    string input;
    getline(cin, input);
    string changeSpace(string input)
    {
        for (int i = 0; i < text.length(); i++)
        {
            if (text[i] == ' ')
                text[i] = '+';
        }
        return text;
    }
    input = changeSpace(input);
    cout << input << endl;
    string url = string(google + input);
    system(string("start " + url).c_str());
    cout << url << endl;
}

The error is here:

string changeSpace(string input)
{

In the bracket it says it expected a " ; "

And I don't know why ocurrs that error, it may be a simple mistake, but I don't know it.

Please help me.

  • 3
    function definitions do not go in functions. – jaggedSpire Aug 22 '16 at 17:46
  • 1
    You made `changeSpace` an inline function in `main` move it above `int main()` – AndyG Aug 22 '16 at 17:46
  • @jaggedSpire: Well, they kind of can with lambdas (although those are really just function objects :-) ) – AndyG Aug 22 '16 at 17:46
  • @AndyG yeah, but those are lambdas. You can also define a struct or class within a function and give it a member function and define a function that way if you're hellbent on defining one but it's still a weaselly way around the "no functions in functions" thing, which is really what lambdas are doing anyway, but I suppose I should have specified *free* functions can't be defined in functions. – jaggedSpire Aug 22 '16 at 17:49

2 Answers2

5

Your problem is because you're trying to define a function inside another function. You cannot do that.

Since C++11, the most similar thing you can do is using lambda.

int main() {
    // stuff...

    auto changeSpace = [] (string text) -> string
    {
        for (int i = 0; i < text.length(); i++)
        {
            if (text[i] == ' ')
                text[i] = '+';
        }
        return text;
    }

    input = changeSpace(input);

    // stuff...
}

But I bet that is not the only error in your code.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
BiagioF
  • 9,368
  • 2
  • 26
  • 50
0

The Nesting of functions is not allowed in c++. Refer this: C++ can we have functions inside functions?

For using system(string("start " + url).c_str()); in your code you should include <cstdlib>. And also use return statement in main :return 0

Community
  • 1
  • 1