Function Placement and '}' Token Error.

Jul 8, 2014 at 5:35pm
Hello! I am still learning the basics of C++ and was trying to write this functions that returns the name of the month corresponding with the number the user inputs (1-12). However I keep getting these two errors.

C:\CPP_Programs\Minigame\ReturnNameOfMonth\main.cpp: In function 'int main()':
C:\CPP_Programs\Minigame\ReturnNameOfMonth\main.cpp:13: error: a function-definition is not allowed here before '{' token
C:\CPP_Programs\Minigame\ReturnNameOfMonth\main.cpp:50: error: expected '}' at end of input
I understand that this code isn't fully finished (as I don't ask the user to cin anything). However, with this problem fixed, it shouldn't be too hard to implement.

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
 #include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;


int main()
{
// int2month() - return the name of the month
   const char* int2month(int nMonth)

   {

       switch(nMonth)
       {
           case 1: pszReturnValue = "January";
           break;
           case 2: pszReturnValue = "February";
           break;
           case 3: pszReturnValue = "March";
           break;
           case 4: pszReturnValue = "April";
           break;
           case 5: pszReturnValue = "May";
           break;
           case 6: pszReturnValue = "June";
           break;
           case 7: pszReturnValue = "July";
           break;
           case 8: pszReturnValue = "August";
           break;
           case 9: pszReturnValue = "September";
           break;
           case 10: pszReturnValue = "October";
           break;
           case 11: pszReturnValue = "November";
           break;
           case 12: pszReturnValue = "December";
           break;
           default: pszReturnValue = "invalid";
       }
       return pszReturnValue;
       }
       system("PAUSE");
       return 0;
   }


}


Thank you all in advance for helping!
Jul 8, 2014 at 5:44pm
Your problem is that you are defining the function within main. You should rather have it outside, and cal it from main. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

const char* int2month(int month) {
     // get the month...
     return pszReturnValue;
}

int main() {
    int month;
    std::cout << "Enter a number from 1-12: ";
    std::cin >> month;

    std::cout << "The corresponding month is " << int2month(month) << "\n";
    return 0;
}
Jul 8, 2014 at 7:34pm
Thank you very much! The function worked perfectly!
Topic archived. No new replies allowed.