簡體   English   中英

將可變長度文件讀入2d char數組

[英]Read variable length file into 2d char array

初學者,試圖將輸入讀入2d char數組。 輸入文件格式為:,,, a,a,a,a ,,,'\\ n',,,,,,,,,,
需要在一個10乘10的數組中,總是有9個逗號而且沒有空格,這就是為什么我有二十二的const int,以防有一個“船”占位符占用空間,在字符中有問題閱讀,當我做閱讀它會跳過所有其他角色。 任何幫助,將不勝感激。

#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;
}

試試這段代碼:

#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;
      }
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM