2016-09-19 17 views
0

私はファイルを整形しようとしてレンガの壁に当たっています。ファイルの書式設定 - C++

0   1   2   3   4   5 
0.047224 0.184679 -0.039316 -0.008939 -0.042705 -0.014458 
-0.032791 -0.039254 0.075326 -0.000667 -0.002406 -0.010696 
-0.020048 -0.008680 -0.000918 0.302428 -0.127547 -0.049475 
... 
6   7   8   9   10   11 
[numbers as above] 
12   13   14   15   16   17 
[numbers as above] 
... 

数字の各ブロックはまったく同じ行数を持っています。私は何をしようとしていることは、私の出力ファイルは次のようになり、最終的にように、第1ブロックの右側にある(ヘッダを含む)すべてのブロックを移動し、基本的である:

0   1   2   3   4   5    6   7   8  9   10   11  ... 
0.047224 0.184679 -0.039316 -0.008939 -0.042705 -0.014458 [numbers] ... 
-0.032791 -0.039254 0.075326 -0.000667 -0.002406 -0.010696 [numbers] ... 
-0.020048 -0.008680 -0.000918 0.302428 -0.127547 -0.049475 [numbers] ... 
... 

だから、最後に、私は基本的に取得する必要がありますnxn行列(数値のみを考慮)。私はすでにこのファイルをフォーマットすることができるpython/bashハイブリッドスクリプトを持っています。 これはちょうど私のコードの実行をLinuxからWindowsに切り替えたので、スクリプトのbash部分をもう使用できません(私のコードはすべてのバージョンのWindowsが準拠します)。正直言って、私はそれをどうするのか分からないので、どんな助けもありがたいです! (...それは私が知っている、完全に間違っているのですが、多分私はそれを構築することができます)

は、ここで私が今まで試したものです:

void finalFormatFile() 
{ 
ifstream finalFormat; 
ofstream finalFile; 
string fileLine = ""; 
stringstream newLine; 
finalFormat.open("xxx.txt"); 
finalFile.open("yyy.txt"); 
int countLines = 0; 
while (!finalFormat.eof()) 
{ 
    countLines++; 
    if (countLines % (nAtoms*3) == 0) 
    { 
     getline(finalFormat, fileLine); 
     newLine << fileLine; 
     finalFile << newLine.str() << endl; 
    } 
    else getline(finalFormat, fileLine); 
} 
finalFormat.close(); 
finalFile.close(); 
} 
+0

「nAtoms」変数とは何ですか?ヘッダーのない行数(1,2,3、...)? –

+0

はい、例えばnAtomsが30の場合、ヘッダーのない行の数は90になります(すべてのアトムに3つの空間座標があるので、これが数値に対応しています)ので、最後には90x90行列ヘッダを除く)。 – JavaNewb

+2

トピックオフ: 'while(!finalFormat.eof())'は一般的なエラーです。もっと詳しくはこちら:http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – user4581301

答えて

0

ようなタスクのために、私はそれを簡単な方法を行うだろう。私たちは既に行の数を知っており、パターンを知っているので、入力ファイルを解析する際に更新する文字列のベクトル(最終ファイルの行ごとに1つのエントリ)を保持しています。それが終わったら、文字列を繰り返して最終的なファイルに出力します。あなたの入力/出力に含まファイルの構造によっては、あなたが右の区切り文字で列を分離するためにラインlines[cnt] = lines[cnt] + " " + lineを調整したい場合があり、

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

int main(int argc, char * argv[]) 
{ 
    int n = 6; // n = 3 * nAtoms 

    std::ifstream in("test.txt"); 
    std::ofstream out("test_out.txt"); 

    std::vector<std::string> lines(n + 1); 
    std::string line(""); 
    int cnt = 0; 

    // Reading the input file 
    while(getline(in, line)) 
    { 
    lines[cnt] = lines[cnt] + " " + line; 
    cnt = (cnt + 1) % (n + 1); 
    } 

    // Writing the output file 
    for(unsigned int i = 0; i < lines.size(); i ++) 
    { 
    out << lines[i] << std::endl; 
    } 

    in.close(); 
    out.close(); 

    return 0; 
} 

注:ここではそれをやっているコードがあります。

+0

すごく、ありがとう!本当にうまくいく:) – JavaNewb