![](/img/trans.png)
[英]Read data from file into 2d array and sum over specific arrays using C++
[英]Read data from file and sum over specific columns after hitting specific line (string) using C++
我決定打開一個新的線程,即使問題已經部分解決但問題是另一個問題( 從文件讀取數據到2d數組並使用C ++對特定數組求和 )。 不過,這是我想要閱讀的內容:
計算點數:200#原子:4
點1:0.00000000 0.00000000 0.00000000加權= 0.00500000
能量1#,加權1.00000000
Atom abcd 1 0.476 0.000 0.000 0.100 2 0.476 0.000 0.000 0.100 1 0.000 -0.000 -0.000 0.200 2 -0.000 -0.000 0.000 0.200
能量2#,加權1.00000000
Atom abcd 1 0.476 0.000 0.000 0.300 2 0.476 0.000 0.000 0.300 1 0.000 -0.000 -0.000 0.400 2 -0.000 -0.000 0.000 0.400
能量2#,加權1.00000000
Atom abcd 1 0.476 0.000 0.000 0.500 2 0.476 0.000 0.000 0.500 1 0.000 -0.000 -0.000 0.600 2 -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
我試圖實現一個布爾值來完成它,但不知怎的,我錯過了一些東西。 如果有人能給我一個提示或告訴我如何解決它,我會非常感激。
感謝您的幫助和豐富的提示!
祝願,DaveS
我找到了解決問題的方法。 我意識到我正在設置“begin_tag = false”,但從未要求它。 再次感謝讀過這篇文章並想過它的人!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.