2015-10-14 108 views
0

所以我需要從文件中讀取一個網格,網格的寬度和長度始終是相同的。問題是當我試圖在最後一行關閉它時,它只顯示大約一半的。從文件C++讀取二維字符數組

#include <iostream> 
#include <fstream> 
#include <cstring> 

using namespace std; 
ifstream TestIn("test"); 


int main() 
{ 

    char Grid[1000][1000],s[1000]; 

    int LungimeX,LungimeY,i,j; 

    TestIn.getline(s,1000); 
    //finding the length 
    LungimeX=strlen(s); 
    cout<<LungimeX<<endl; 

    //finding the width 
    while (!TestIn.eof()) { 
     TestIn.getline(s,1000); 
     LungimeY++; 
    } 
    cout<<LungimeY; 

    //reset .eof 
    TestIn.clear(); 
    TestIn.seekg(0, TestIn.beg); 

    //get the grid into the array 
    for(i=1;i<=LungimeY;i++) { 
    for(j=1;j<=LungimeX;j++) { 
     TestIn.get(Grid[i][j]); 
    }} 

    for(i=1;i<=LungimeY;i++){ 
    for(j=1;j<=LungimeX;j++){ 
     cout<<Grid[i][j]; 
    }} 

    return 0; 
} 

所以是的,任何想法如何解決這個問題?

+0

你能上傳你正在嘗試閱讀的文件嗎? – Minato

+1

http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong –

+0

只是一個猜測:輸入文件是否包含換行符('\ n ')?可能是的,所以他們會讀入Grid,這是你不想要的。另一件事是你使用數組爲1',C++中的索引從0開始。 Grid [0] [1000] 是錯誤的。 –

回答

0
  1. LungimeY未初始化
  2. 需要的文件倒帶之後讀取(跳過)標題行
  3. 需要跳過CR和/或LF的字符之後填充所述陣列
  4. 當每一行讀
0

你沒有忽略換行符LungimeX是不包括換行符的行的長度。遇到換行符時讀取文件時可能會遇到一個簡單的解決方案,即讀取下一個字符。 的#include 的#include 的#include

using namespace std; 
ifstream TestIn("test"); 


int main() 
{ 

    char Grid[1000][1000],s[1000]; 

    int LungimeX,LungimeY,i,j; 

    TestIn.getline(s,1000); 
    //finding the length 
    LungimeX=strlen(s); 
    cout<<LungimeX<<endl; 

//finding the width 
      while (!TestIn.eof()) { 
       TestIn.getline(s,1000); 
      LungimeY++;} 
cout<<LungimeY; 

//reset .eof 
TestIn.clear(); 
TestIn.seekg (0, TestIn.beg); 

//get the grid into the array 
for(i=1;i<=LungimeY;i++){ 
for(j=1;j<=LungimeX;j++){ 
    TestIn.get(Grid[i][j]); 
    if(Grid[i][j] == '\n') //check new line character 
     TestIn.get(Grid[i][j]); 
}} 

for(i=1;i<=LungimeY;i++){ 
for(j=1;j<=LungimeX;j++){ 
    cout<<Grid[i][j]; 
} 
cout<<endl; 
} 



    return 0; 
} 

而且是請使用用C 0索引++你是在浪費內存這種方式。

0

這種更多的C++方法呢?

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

int main() 
{ 
    std::string fname("test.txt"); 
    std::ifstream f(fname.c_str()); 

    std::vector<std::string> lines; 
    std::string line; 
    while(std::getline(f, line)) 
     lines.push_back(line); 

    unsigned long int num_rows = lines.size(); 
    unsigned long int num_cols = 0; 
    if(num_rows > 0) 
     num_cols = lines[0].length(); 

    std::cout << "num_rows = " << num_rows << std::endl; 
    std::cout << "num_cols = " << num_cols << std::endl; 

    for(unsigned long int i = 0; i < num_rows; ++i) 
    { 
     for(unsigned long int j = 0; j < num_cols; ++j) 
      std::cout << lines[i][j]; 
     std::cout << std::endl; 
    } 

    return 0; 
}