Use of string arrays in functions?

Hi, I have the following code which works, but can someone please help me with how I may instead put the tasks of populating the array and printing the array in two separate functions, and how I may call those functions? I can do it if it was an array of integers or something like that but it doesn't work for me with an array of strings. Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int main () {


//Populate array:
char *months[] = {"January","February","March","April"};


//Print array:
for (int i=1;i<3;i++) {
     cout << months[i] << endl;
}

return 0;
}
One way to do it is this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

const char * months[]={"January","February","March","April"};

void print_months();

int main()
{
    print_months();

    return 0;
}

void print_months()
{
    for (int i=0;i<4;i++)
        cout << months[i] << endl;
}

Another way to do it is this:

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
#include <iostream>
#include <string>
#include <vector>
using namespace std;

void init_months(vector<string> & m);
void print_months(vector<string> & m);

int main()
{
    vector<string> months;

    init_months(months);
    print_months(months);

    return 0;
}

void init_months(vector<string> & m)
{
    m.push_back("January");
    m.push_back("February");
    m.push_back("March");
    m.push_back("April");
}

void print_months(vector<string> & m)
{
    for (int i=0;i<4;i++)
        cout << m[i] << endl;
}
Topic archived. No new replies allowed.