使用c++从文件中读取数据,并在击中特定行(字符串)后对特定列求和
Read data from file and sum over specific columns after hitting specific line (string) using C++
我决定打开一个新的线程,即使问题已经部分解决,但问题是另一个现在(读取数据从文件到2d数组和求和特定数组使用c++)。尽管如此,以下是我想读的内容:
计算个数:200 # Atoms: 4
点1:0.00000000 0.00000000 0.00000000权重= 0.00500000
权重为100000000的能量1 #
原子a b c d1 0.476 0.000 0.000 0.1002 0.476 0.000 0.000 0.1001 0.000 -0.000 -0.000 0.2002 -0.000 -0.000 0.000 0.200
权重为100000000的能量2 #
原子a b c d1 0.476 0.000 0.000 0.3002 0.476 0.000 0.000 0.3001 0.000 -0.000 -0.000 0.4002 -0.000 -0.000 0.000 0.400
权重为100000000的能量2 #
原子a b c d1 0.476 0.000 0.000 0.5002 0.476 0.000 0.000 0.5001 0.000 -0.000 -0.000 0.6002 -0.000 -0.000 0.000 0.600
…
…
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
int rows = 0;
int columns = 0;
string line;
int firstNumber = 0;
vector<vector<double> > values;
vector<vector<double> > results;
vector<double> rowstotal;
ofstream File;
ifstream in("data.txt");
File.open("Output.txt",ios::app);
File.setf(ios::fixed);
File.setf(ios::showpoint);
File.precision(3);
if(in.fail())
{
cerr << "File can not be opened" << endl;
return -1;
}
File << "n" << endl;
// Save every double
while(in.good())
{
bool begin_tag = false;
while (getline(in,line))
{
if(line.find("Energy 2 #") != std::string::npos ) {
begin_tag = true;
continue;
}
else if (line == "Energy 1 #")
{
begin_tag = false;
}
istringstream stream(line);
vector<double> tmp;
double x;
while (stream >> x)
tmp.push_back(x);
if (tmp.size() > 0)
values.push_back(tmp);
}
}
columns = values[0].size();
for (unsigned i = 1; i < values.size(); ++i)
{
if (values[i].size() != columns)
{
cerr << "Row with different column number" << endl;
return -1;
}
}
for (unsigned i = 0; i < values.size(); ++i)
{
// If number with 1.0 is encountered, add it to the row
if (values[i][0] == 1.0)
results.push_back(values[i]);
// If number with 2.0 is encountered, add it also to the row
if (values[i][0] == 2.0)
{
for (unsigned j = 0; j < values[i].size(); ++j)
results.back()[j] += values[i][j];
}
}
rows = results.size();
File << "Number of rows # " << rows << endl;
File << "Number of columns # " << columns << endl;
File << " " << endl;
for(int i=0; i < rows; i++)
{
for(int j=4; j < columns; j++)
{
File << results[i][j] << " " << " " << endl;
}
}
for(int i=0; i < rows; i++)
{
rowstotal.push_back(0.0);
for (int j=1; j < columns; j++)
{
rowstotal[i] += results[i][j];
}
}
File.close();
in.close();
return 0;
}
输出为:
行数# 6列数# 5
0.200
0.400
0.600
0.800
1.000
1.200
如上所述,我想要实现的是只对"能源2 #"区块求和,而忽略以"能源1#"开始的区块。所以代码应该给出值:
0.600
0.800
1.000
1.200
我试图实现一个布尔值来完成它,但不知何故我错过了一些东西。如果有人能给我一个提示或告诉我如何解决这个问题,我将非常感激。
感谢任何帮助和富有成效的提示!
最好的祝愿,daf)
我找到了解决问题的方法。我意识到我正在设置"begin_tag = false",但从来没有要求它。再次感谢任何阅读这篇文章并思考它的人!