I have now changed my code to use a vector instead of an array and everything is working ok, but I have an issue with one of the vector's.
I have had to declare the vector "code" globally to get the program to work, but my understanding is that, by declaring it globally the vector is allocated when the program starts, then deallocated when the program ends, which seems pointless, is this correct?
I am wanting to have it allocated when merge_code is first called, then deallocated when write_code has returned, can I do this with the vector "code"?
If not, is it possible to pass a vector to a dynamic 2d array? then could I make "code" a dynamic 2d array so I can allocate\deallocate it where I want.
Code:
vector< vector<string> > code(HEIGHT*25, vector<string>(WIDTH));
int main(void)
{
int x;
do{
cout << "\n1. some \t2. other \t0. quit" << endl;
cin >> x;
globalCO.clear_ibuffer();
switch(x)
{
case 1:
someCO.somefunc();
break;
case 2:
otherCO.otherfunc();
break;
default:
x = 0;
break;
}
}while(x != 0);
globalCO.write_code();
return 0;
}
void globalC::write_code(void)
{
ofstream outdata;
outdata.open("c:\\output.txt");
if( !outdata )
{
cerr << "Error: file could not be opened" << endl;
exit(1);
}
for (int n=0;n<HEIGHT*25;n++)
for (int m=0;m<WIDTH;m++)
outdata << code.at(n).at(m);
outdata.close();
}
void globalC::merge_code(vector< vector<string> > &pvec_code)
{
pHEIGHT = &indexH;
if (array_count == 1)
{
for(int n=0;n<HEIGHT; n++)
for(int m=0;m<WIDTH; m++)
code.at(n).at(m) = pvec_code.at(n).at(m);
*pHEIGHT = 10;
}
else if (array_count == 2)
{
for(int n=0;n<HEIGHT; n++, indexH++)
for(int m=0;m<WIDTH; m++)
code.at(indexH).at(m) = pvec_code.at(n).at(m);
*pHEIGHT = 20;
}
// More else if statements....
}
void globalC::add_double_quotes(string &str)
{
str = '\"' + str + '\"';
}
void globalC::clear_ibuffer(void)
{
cin.clear();
cin.ignore(100, '\n');
}
void someC::some_func(void)
{
int x;
string uinput;
vector< vector<string> > some_code(HEIGHT, vector<string>(WIDTH));
cout << "1. group \t2. rank \n3. rank1 \t4. name \n0. quit\n" << endl;
do{
cin >> x;
globalCO.clear_ibuffer();
switch(x)
{
case 1:
some_code.at(0).at(0) = "group";
break;
case 2:
some_code.at(1).at(0) = "rank";
break;
case 3:
some_code.at(1).at(1) = "rank1";
break;
case 4:
getline(cin, uinput);
default:
x = 0;
break;
}
}while(x != 0);
sort_string(uinput, some_code);
}
void someC::sort_string(string &str, vector< vector<string> > &psome_code)
{
// This function is used to sort the user input and add more code to, if necessary
globalCO.merge_code(psome_code);
}
void otherC::other_func(void)
{
int x;
string uinput;
vector< vector<string> > other_code(HEIGHT, vector<string>(WIDTH));
// Similar to someC::some_func
sort_string(uinput, other_code);
}
void otherC::sort_string(string &str, vector< vector<string> > &pother_code)
{
// This function is used to sort the user input and add more code to, if necessary
globalCO.merge_code(pother_code);
}