2

ファイルを垂直方向にトラバースする必要があります。ファイルの内容が次の場合:

adg
beh
cfi

ファイルは次のように出力されます。

abc
def
ghi

各行の長さは同じになります (つまり、上記の例ではすべての行の長さが 3 になります)。コードを書きましたが、必要に応じてファイルをトラバースしません。

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
    fstream fs;
    fs.open("asd.txt",ios::in);
    string str;
    char *ch = new char();
    int lineLen = 0, k = 0;
    if(getline(fs,str))
    {
        lineLen = str.length();
    }
    fs.seekg(0);
    if(lineLen > 0)
    {
    for(int i = 0;i<lineLen;i++)
    {
        fs.seekg(i+k*lineLen);
        while(fs.read(ch,1))
        {
            k++;
            fs.seekg(i+k*lineLen);
            cout<<*ch;
        }
        k = 0;
    }
    }
    fs.close();
    cin.ignore();
}

私はファイル処理に少し慣れていないので、間違いを見つけることができませんでした。また、これに従うためのより良いアプローチはありますか?

4

5 に答える 5

1

ソース ファイルで seek() を繰り返し実行する代わりに、ソース ファイル全体を単純に読み取り、メモリ内の内容から出力を生成する方がはるかに簡単で高速です。

これはクラスの課題のようにひどいように聞こえるので、簡単に答えを書くことはしません. ただし、これは正しい方法を示しているはずです-いくつかの PseodoCode が含まれています

苦痛を避けるために、おそらく、行の長さと最大行数の上限を想定するのが安全であるはずです。つまり、

const int MaxLines = 100;
const int MaxLength = 80;

int lineno, linelength;

// array of char pointers for each line
char *lines[] = (*lines[])malloc(Maxlines * sizeof(char*));

// ReadLoop
lineno = 0;
while (not eof)
{
  getline(buffer);
  if (++lineno++ == 1)
  {
    linelength = strlen(buffer);
  }
  else
  {
    if (linelength != strlen(buffer))
    {
      cout "Line # " << lineno << " does not match the expected length";
      exit();
    }
  } 
  lines[lineno] = malloc(strlen(buffer)+1));
  strcpy(lines[lineno], buffer);
}

int cc, linecnt = lineno;

// now all data in memory, output "vertical data"
for (cc = 0; cc < linelength; ++cc)
{
  for (lineno=0; lineno<<linelength; ++lineno)
  {
     cout << lines[xx][yy]; // xx && yy left you to figure out
  }
  cout "\n";
}
于 2013-08-30T17:24:07.993 に答える
1

あなたにいくつかのアイデアを与えるかもしれないテストされていない疑似コード。基本的に、簡単にアクセスできるように、ファイル全体を文字の 2 次元ベクトルにロードします。ファイルから直接読み取るよりも多くのメモリを使用しますが、ファイルが非常に大きい場合を除き、これは問題になりません。

vector<vector<char>> filemap;
string line;
while (getline(filestream, line))
{
    filemap.push_back(vector<char>(line.begin(), line.end()));
}

for (int x = 0; x < XSIZE; x++)
{
    for (int y = 0; y < YSIZE; y++)
    {
        filestream << filemap[y][x]; // note x/y are opposite way round in 2d vectors
    }
    filestream << '\n';
}
于 2013-08-30T17:08:46.773 に答える