2014-11-07 28 views
0

我正在編寫一個代碼來顯示一個文件中的數組,這一切都在具有.h文件.cpp文件和主文件的項目中完成。但是我的頭文件一直給我'class token'的錯誤redefiniton和'class token'的珍貴定義,但我不確定如何重新定義它。感謝您的幫助在C++中使用二維數組的類的錯誤

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文件頭文件

+0

是否有適當的標頭警衛?請參閱:http://stackoverflow.com/questions/8020113/c-include-guards – rockoder 2014-11-07 02:00:27

回答

0

就行

matrix[30][30].setassign(filename); 

您試圖引用2D數組中的超出範圍的項目。您可以使用的元素在範圍矩陣[0] [0]到矩陣[29] [29]中。矩陣[30] [30]超出界限。

記得在C++中,當您的分配10例如第一元件是在索引0處的最後一個(或第十元件)的陣列是在索引9.