2016-09-19 77 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