2016-01-03 48 views
3

我剛開始一個小項目,讀取TXT文件是這樣的:如何從一個txt文件中讀取一個迷宮,並把它變成二維數組

4 
XSXX 
X X 
XX X 
XXFX 

所以我的問題是怎麼看這一點,並把迷宮到C++中的二維字符數組。我試圖使用'getline',但我只是讓我的代碼更復雜。你知道是否有簡單的方法來解決這個問題?

char temp; 
    string line; 
    int counter = 0; 
    bool isOpened=false; 
    int size=0; 

    ifstream input(inputFile);//can read any file any name 
    // i will get it from user 

    if(input.is_open()){ 

    if(!isOpened){ 
     getline(input, line);//iterater over every line 
     size= atoi(line.c_str());//atoi: char to integer method.this is to generate the size of the matrix from the first line   
    } 
    isOpened = true; 
    char arr2[size][size];  

    while (getline(input, line))//while there are lines 
    { 
     for (int i = 0; i < size; i++) 
     { 

      arr2[counter][i]=line[i];//decides which character is declared 

     } 
     counter++; 
    } 
+1

顯示你寫的內容並解釋它是如何不足的。 –

+2

不要問_「給我的代碼plz」_,顯示你已經做了什麼,爲什麼它不適合你首先請。 –

+0

我剛剛編輯了我的問題。 – Syrenthia

回答

3

你的錯誤是由於這樣的事實,你試圖用一個大小是一個非常量表達式聲明數組。

在你的情況下,size代表數組中元素的數量,因爲數組是在程序運行前必須在編譯時確定大小的靜態存儲區塊,所以它必須是constant expression

爲了解決這個問題您可以保留空托架和大小的數組將元素的數量自動推斷你在裏面放置或 你可以使用std::stringstd::vector,然後讀取.txt文件,你可以寫是這樣的:

// open the input file 
ifstream input(inputFile); 

// check if stream successfully attached 
if (!input) cerr << "Can't open input file\n"; 

string line; 
int size = 0;  

// read first line 
getline(input, line); 

stringstream ss(line); 
ss >> size; 

vector<string> labyrinth; 

// reserve capacity 
labyrinth.reserve(size); 

// read file line by line 
for (size_t i = 0; i < size; ++i) { 

    // read a line 
    getline(input, line); 

    // store in the vector 
    labyrinth.push_back(line); 
} 

// check if every character is S or F 

// traverse all the lines 
for (size_t i = 0; i < labyrinth.size(); ++i) { 

    // traverse each character of every line 
    for (size_t j = 0; j < labyrinth[i].size(); ++j) { 

     // check if F or S 
     if (labyrinth[i][j] == 'F' || labyrinth[i][j] == 'S') { 

      // labyrinth[i][j] is F or S 
     } 

     if (labyrinth[i][j] != 'F' || labyrinth[i][j] != 'S') { 

      // at least one char is not F or S 
     } 
    } 
} 

正如你可以看到這vector已經是「一種」只用了很多額外提供設施,允許在它的內容很多操作2D char陣列。

+0

那麼如何讓每個角色檢查它是'S'還是'F'?或者有什麼辦法可以把這個矢量化爲2D字符數組? – Syrenthia

+0

我會編輯我的答案來檢查它是'S'還是'F' – Ziezi

+1

現在我試試它.. – Syrenthia

相關問題