C++中使用二维数组的类错误
我正在编写一个代码来显示一个文件中的数组,这都是在一个包含.h file.cpp文件和一个主文件的项目中完成的。然而,我的头文件不断给我错误的“类令牌”重新定义和宝贵的“类令牌”定义,但我不太确定如何重新定义它。谢谢你的帮助C++中使用二维数组的类错误,c++,C++,我正在编写一个代码来显示一个文件中的数组,这都是在一个包含.h file.cpp文件和一个主文件的项目中完成的。然而,我的头文件不断给我错误的“类令牌”重新定义和宝贵的“类令牌”定义,但我不太确定如何重新定义它。谢谢你的帮助 main.cpp using namespace std; int main() { string filename; int b; int d; int i; int j; token matrix[30][30]; cout << "Type the n
main.cpp
using namespace std;
int main()
{
string filename;
int b;
int d;
int i;
int j;
token matrix[30][30];
cout << "Type the name of text file: e.g. 'File.txt'" << endl;
getline( cin, filename );//This could also be cin >> name//
matrix[30][30].setassign( filename );
cout << endl ;
system("pause") ;
}
token.h
// header file token.h
using namespace std;
class token
{
private:
string assignmat;
//char displaymat;
//char displaytoken;
public:
// Constructors
token();
token( string );
//token( string, char, char );
// Public functions
void setassign( string );
//void setdisplay( char );
//void settoken( char );
};`
token.cpp
using namespace std;
// constructor 1
token::token()
{
assignmat = " ";
//displaymat = ' ';
//displaytoken = ' ';
}
// constructor 2 parameterised constructor
token::token( string assignmat1) //, int displaymat1, char displaytoken1 )
{
assignmat = assignmat1;
//displaymat = displaymat1;
//displaytoken = displaytoken1;
}
// public function setName
void student::setassign( string filename )
{
char matrix[30][30];
ifstream inputFile;
int i,j;
inputFile.open(filename.c_str());
for(i = 0; i < b; i++)
{
for(j = 0; j < d; j++)
{
inputFile.get(matrix[i][j]);
if(matrix[i][j] == ',' || matrix[i][j] == '\n') // for some reason if i dont include the \n it doesnt work, but it should because the row ends at 30
{ //if loop to get rid of commas by deducting the counter by 1, hence replacing the comma with the next value
j-- ;
}
}
}
cout << endl;
for(i = 0; i < b; i++){ // display
for(j = 0; j < d; j++){
cout << " " << matrix[i][j] ;
}
cout << endl ;
}
}
很抱歉,我是这个论坛的新手,不知道如何使用它,我还将头文件包括在我的主文件和.cpp文件中
matrix[30][30].setassign( filename );
您试图引用二维数组中超出边界的项。您可以使用的元素在矩阵[0][0]到矩阵[29][29]的范围内。矩阵[30][30]超出范围
记住C++中,当你分配一个数组10时,例如第一个元素在索引0,最后一个元素或者第十个元素在索引9。参考: