2017-03-26 15 views
1

初心者の学生に可変長ファイルをお読みください。 入力ファイル形式は:,,,、、、,,,「\ n」は,,,,,,,,,
が10×10アレイにする必要があり、常に9つのコンマを有し、何のスペースは、私は場合には20で私のconst int型を持っている理由があることを「船」のプレースホルダは、問題の文字で読みを持つスペースを取っていないと私は他のすべての文字をスキップするでしょう、それを読み込むために手に入れたとき。 ご協力いただければ幸いです。2D char型の配列への入力を読み取ろうとする、2D char配列

#include <iostream> 
#include <fstream> 
#include <cstdlib> 

using namespace std; 
bool checkship(); 
string filename; 
ifstream inputfile; 
int rowcount= 0, colscount=0; 
const int rows=20, cols=20 ; 
char boardarray[rows][cols]; 

int main() 
{ 
    cout<< "input your battlestation board filename: " << endl; 
    cin >> filename; 
    inputfile.open(filename.c_str()); 
    while(!inputfile) 
    { 
     cout << "file did not oipen please retry"; 
     cin >> filename; 
     inputfile.open(filename.c_str()); 
    } 

    while(inputfile) 
    { 
     for(rowcount=0;rowcount < rows;rowcount++) 
     { 
     for(colscount=0; colscount < cols; colscount++) 
     { 
      char ch; 
      inputfile >> ch; 

      while(ch!= '\n') 
      { 
       inputfile >> boardarray[rowcount][colscount]; 
      } 
      if(ch = '\n') 
      { rowcount++; 
       colscount= 0; 
      } 
     }                                          } 
    } 
    inputfile.close(); 

    for(rowcount=0; rowcount <10 ; rowcount++) 
    { 
     for(colscount=0; colscount< cols; colscount++) 
     { 
     cout << boardarray[rowcount][colscount]; 
     if(colscount == 9) 
      cout << endl; 
     } 
    } 

    return 0; 
} 
+0

内容私には明確ではありません。 'INPUTFILE >> boardarray [行数] [colscount];'ファイル内の任意の空白文字がある場合、問題になります。 –

+0

[あなたのロジックを簡素化に役立つと 'のstd :: getline'を見つけることができます。](http://en.cppreference.com/w/cpp/string/basic_string/getline)の助けを – user4581301

答えて

0

このコードを試してみてください:ファイルの

#include <iostream> 
#include <fstream> 
#include <cstdlib> 

using namespace std; 

string filename; 
ifstream inputfile; 
int rowcount= 0, colscount=0; 
const int max_rows=20, max_cols=20 ; 
char boardarray[max_rows][max_cols]; 

int main() 
{ 
    cout<< "input your battlestation board filename: " << endl; 
    cin >> filename; 
    inputfile.open(filename.c_str(), ios::in | ios::binary); 
    while(!inputfile) 
    { 
     cout << "file did not oipen please retry"; 
     cin >> filename; 
     inputfile.open(filename.c_str(), ios::in | ios::binary); 
    } 

    while(!inputfile.eof()) 
    { 
     char ch = 0; 
     colscount = 0; 
     while(ch!= '\n' && !inputfile.eof()) 
     { 
      inputfile.read(&ch, 1); 
      if (ch != '\r' && ch!='\n') { 
       if (ch != ',') { 
        boardarray[rowcount][colscount] = ch; 
       } else { 
        colscount++; 
       } 
      } 
     } 
     rowcount++; 
     colscount++; 
    } 
    inputfile.close(); 

    for(int i=0; i < rowcount; i++) 
    { 
     for(int j=0; j< colscount; j++) 
     { 
     cout << boardarray[i][j]; 
     if(j == (colscount-1)) 
      cout << endl; 
     } 
    } 
} 
+0

おかげで、病気にこれを与えます一発。この問題に長続きしていませんでした。 @ user3811082 – Ftank

関連する問題