(a function-definition is not allowed here before ‘{’) What's wrong?

My code is supposed to guess a number the user thought of that is between 0 and 100. It generates a different number each time, and prompts the user if it is the right number. The code compiles with no errors, except two ones I know nothing about. It uses a while loop to repeat the process.
Here's my 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <unistd.h>
#include <string>

using namespace std;

int main() {
  bool repeat = false;
  bool guessedright = false;
  cout << "Please think of a random number between 0 and 100" << endl;
  sleep(1);
  cout << "Did you finish thinking? Press the return key when you are ready";
  cin.get();
  while (!guessedright)
  {
    int rand_lim(int limit) {
    int divisor = RAND_MAX/(limit+1);
    int retval;

    do { 
        retval = rand() / divisor;
    } while (retval > limit);
    return retval;
    }
    int random_num = rand_lim(100);
    string current;
    current = random_num;
    string num_try;
    num_try += random_num + " ";
    if (num_try.find(current) != std::string::npos) 
    {
    repeat = true;
    }
    if (repeat)
    {
      continue;
    }
    else
    {
      char a;
      cout << endl << "My guess is " << random_num 
           << ". If it is right type \'y\' or \'n\' " 
           << "if it is wrong: " << endl;
      cin >> a;
      if (a=='y' || a=='Y')
      {
	guessedright = true;
      }
      else if (a=='n' || a=='N')
      {
	continue;
      }
      else
      {
	cout << "WHAT was that?? I will take it as wrong anyway!" << endl;
	guessedright = false;
	continue;
      }
  }
    cout << "Yeah! Yeah babe... I WIN!";
    return 0;
}
}

and here is the error KDevelop and g++ give me:

main.cpp: In function ‘int main()’:
main.cpp:18:29: error: a function-definition is not allowed here before ‘{’ token
int rand_lim(int limit) {
^
main.cpp:63:1: error: expected ‘}’ at end of input
}
^
main.cpp:63:1: error: expected ‘}’ at end of input

The strange thing is, even when I add two '}''s to the end of the code it gives the same error. I am still learning C++, and I don't understand what's wrong with the first error. I appreciate your sacrificing of time for me.

Last edited on
it's pretty much telling you.
line 18:
1
2
3
4
int rand_lim(int limit) {

...
}


that's nonsense.
You cant put a function implementation in the middle of a while loop.
Last edited on
You cant put a function implementation in the middle of a while loop.

Or, indeed, anywhere inside another function.
well, yea :)
Well, sorry I didn't know that. Thanks.
Last edited on
Topic archived. No new replies allowed.