2016-09-19 74 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] 
... 

每個數字塊的行數都完全相同。我的輸出文件應該是這樣的我所試圖做的是基本上每移動塊(包括標題),以第一個塊的右側,這樣在最後:

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

Off topic:'while(!finalFormat.eof())'是一個常見錯誤。在這裏閱讀更多:http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – user4581301

回答

0

對於這樣的任務,我會做的簡單方法。因爲我們已經知道了行數,並且我們知道這個模式,所以我會簡單地保留一個字符串向量(最終文件的每行一個條目),我會在解析輸入文件時進行更新。一旦完成,我會遍歷我的字符串將它們打印到最終文件中。下面是在做它的代碼:

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

需要注意的是,根據您的輸入/輸出中文件的結構,你可能需要調整行lines[cnt] = lines[cnt] + " " + line以列用正確的分隔符分開。

+0

真棒,非常感謝你!作品真的很好:) – JavaNewb