multidimensional string c++
I'm writing a function that has a 2D array of strings as input parameter. I initialized the string, passed it to the function but when I tried to print the array nothing happened. It says that the length of the array is 0. All my functions are stored in a header file. Here's my code:
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
int c,i,j,fx,fy;
int color,fields,rows,anim,speed;
string opt[5][50];
string popt[5][50]={
{"caption","asdf","safd","asf"},
{"caption1","dsafa","asdf","asdf"},
{"caption2","asdf","asdf","asdfas"},
{"caption3","sadfa","asdfs","fasdfa"}};
void ini(int focus_text_color, int n_fields,int n_rows, string options[][50], bool animation=false, int animation_speed=10)
{
color=focus_text_color;
fields=n_fields;
for(i=1;i<fields+1;i++)
{
for(j=1;j<rows+1;j++)
{
opt[i][j]=options[i][j];
}
}
}
int drawh()
{
system("cls");
for(i=0;i<fields;i++)
{
for(j=0;j<rows;j++)
{
cout<<opt[i][j]<<setw(opt[i+1][j].length()+5);
}
}
return 0;
}
void main()
{
ini(LIGHTRED,4,4,popt);
drawh();
}
NOTE: This is a part of the code so I haven't 开发者_运维技巧tested it, and sorry for my bad English :D
Apart from @Oli's comments. To make it simpler, you can pass an array by reference. See below example:
template<unsigned int ROW, unsigned int COL>
void ini (string (&s)[ROW][COL]) // psuedo code for 'ini'; put extra params to enhance
{
ini(s, ROW, COL);
}
Now, template ini()
provides a wrapper to actual ini()
which calculates the row/column of an array at compile time. Usage is very simple:
string s[10][5];
ini(s); // calls ini(s,10,5);
Your loop should start from dimension 0
and not 1
for copying. Check my approach and modify your code.
for(int i = 0; i < ROW; i++)
for(int j = 0; j < COL; j++)
s1[i][j] = s2[i][j];
Also there are many problems in your code due to passing wrong dimensions (e.g. passing 4
as dimension while calling ini()
, when it should be 5).
The reason why you don't get any output is that you don't initialize the global variable rows
, so it stays at 0. Your init
function should be:
void ini(int focus_text_color, int n_fields,int n_rows, string options[][50], bool animation=false, int animation_speed=10)
{
color=focus_text_color;
fields=n_fields;
rows = n_rows; //-- ADDED LINE
....
精彩评论