格式化文件- c++

Formatting files - C++

本文关键字:c++ 文件 格式化      更新时间:2023-10-16

我在尝试格式化我的一个文件时遇到了瓶颈。我有一个文件,我把它格式化成这样:

 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();
}

对于这样的任务,我将采用简单的方法。由于我们已经知道了行数和模式,我将简单地保留一个字符串向量(最终文件的每行一个条目),以便在解析输入文件时更新它。完成后,我将遍历字符串,将它们打印到最终文件中。下面是这样做的代码:

#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行,以便用正确的分隔符分隔列。