2015-05-25 63 views

回答

2

檢查一個矩陣的初始化代碼,它應該是int level[HEIGHT][WIDTH];而不是int level[WIDTH][HEIGHT];也是,你的數據行比WIDTH短。代碼的工作方式如下:我們遍歷一個級別矩陣的所有行,通過(file >> row)指令從文件中讀取一行,如果讀取成功,則我們將行填充到級別矩陣中,否則我們讀取EOF以便從循環中斷開。

#include<iostream> 
    #include<fstream> 
    #include<string> 
    #include <limits> 

    static const int WIDTH = 100; 
    static const int HEIGHT = 25; 

    int main() 
    { 
     int level[HEIGHT][WIDTH]; 

     for(int i = 0; i < HEIGHT; i++) 
     { 
      for(int j = 0; j < WIDTH; j++) 
      { 
       level[i][j] = 0; 
      } 
     } 

     std::ifstream file("Load/Level.txt"); 
     for(int i = 0; i < HEIGHT; i++) 
     { 
      std::string row; 
      if (file >> row) { 
       for (int j = 0; j != std::min<int>(WIDTH, row.length()) ; ++j) 
       { 
        level[i][j] = row[j]-0x30; 
       } 
       std::cout << row << std::endl; 
      } else break; 
     } 

     return 0; 
    } 
+0

這工作!另外,你的數據行是什麼意思? –

+0

文件http://pastebin.com/d3PWqSTV中的行少於100 – nikitoz

+0

哦真的沒有注意到!謝謝 –

0

可以使用file >> level[i][j];level.txt內容來填充您的2D字符數組level[ ][ ]

#include<iostream> 
#include<fstream> 
#include<string> 
using namespace std; 

static const int WIDTH = 100; 
static const int HEIGHT = 25; 
char level[HEIGHT][WIDTH]={0}; 


int main() 
{ 

    std::ifstream file; 
    file.open("level.txt"); 

    if(file.is_open()) 
    { 
      std::cout << "File Opened successfully!!!. Reading data from file into array" << std::endl; 
      while(!file.eof()) 
      { 
        for(int i = 0; i < HEIGHT; i++) 
        { 
          for(int j = 0; j < WIDTH; j++) 
          { 
            //level[i][j] = ??? 
            file >> level[i][j]; 
            std::cout << level[i][j]; 
          } 
          std::cout << std::endl; 
        } 
      } 

    } 
    file.close(); 

    return 0; 
} 
+0

這不起作用,因爲帶有數據的文件不包含空格。 – nikitoz

+0

是的,我試過了,但這不適合我... –

+0

@nikitoz哦,這就是爲什麼! –

相關問題