多维字符串 C++
multidimensional string c++
我正在编写一个函数,该函数将字符串的 2D 数组作为输入参数。我初始化了字符串,将其传递给函数,但是当我尝试打印数组时,没有任何反应。它说数组的长度为 0。我所有的函数都存储在一个头文件中。这是我的代码:
#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();
}
注意:这是代码的一部分,所以我还没有测试过它,很抱歉我的英语:D不好
除了@Oli的评论。为了更简单,您可以通过引用传递数组。请参阅以下示例:
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);
}
现在,template ini()
提供了一个实际ini()
的包装器,用于在编译时计算数组的行/列。用法非常简单:
string s[10][5];
ini(s); // calls ini(s,10,5);
循环应从维度 0
开始,而不是1
复制。检查我的方法并修改您的代码。
for(int i = 0; i < ROW; i++)
for(int j = 0; j < COL; j++)
s1[i][j] = s2[i][j];
此外,由于传递错误的维度,代码中也存在许多问题(例如,在调用ini()
时将4
作为维度传递,而它应该是 5)。
你没有得到
任何输出的原因是你没有初始化全局变量 rows
,所以它保持在 0。您的init
函数应为:
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
....