我有一个代码,我可以用它在屏幕上显示输出。但是,我想把输出放在一个文本文件中。坦率地说,我读过 Lambda 表达式,但我很难理解它的功能(因为我是初学者)。
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
#include <vector>
using Matrix = std::vector<std::vector<float>>;
void addRow(Matrix& M, const int rowNum, const int id, const float type, const float x, const float y,const float z) {
M[rowNum][0] = id;
M[rowNum][1] = type;
M[rowNum][2] = x;
M[rowNum][3] = y;
M[rowNum][4] = z;
}
int main() {
string line;
float x0, y0, z0, x1, y1, z1, type;
int NUMBER_line=0, id=0,NUMBER_line1=0,NUMBER_line3=0;
ofstream secondoutput; // the output text file
secondoutput.open ("secondoutput.txt"); // the output text file
ifstream myfile("1.lammpstrj");
string namefile;
if (myfile.is_open()) {
for (int lineno = 0; getline(myfile, line) && lineno < 7; lineno++) {
if (lineno == 2) myfile >> NUMBER_line;
}
cout << " NUMBER_line: " << NUMBER_line << endl;
Matrix Input0(NUMBER_line, std::vector<float>(5));
for (float linenoq = 0; getline(myfile, line) && linenoq < NUMBER_line; linenoq++) {
myfile >> id >> type >> x0 >> y0 >> z0;
addRow(Input0, linenoq, id, type, x0, y0, z0);
}
for (int i=0; i <3; i++){
for (int lineno = 0; getline(myfile, line) && lineno < 7; lineno++) {
if (lineno == 2) myfile >> NUMBER_line1;
}
Matrix Input1(NUMBER_line1, std::vector<float>(5));
for (int linenoq = 0; getline(myfile, line) && linenoq < NUMBER_line1; linenoq++) {
myfile >> id >> type >> x1 >> y1 >> z1;
addRow(Input1, linenoq, id, type, x1, y1, z1);
}
Matrix Output(NUMBER_line, std::vector<float>(5));
for (size_t row = 0; row < Output.size(); ++row) {
for (size_t col = 0; col < Output[0].size(); ++col) {
if (col < 2) {
Output[row][col] = Input0[row][col];
}
else {
Output[row][col] = Input1[row][col] - Input0[row][col] ;
}
}
}
std::for_each(Output.cbegin(), Output.cend(),
[](auto const& row) {
std::for_each(row.cbegin(), row.cend(),
[](const float value) {
cout << value << " ";
secondoutput << value << " "; // the output text file
});
cout << endl;
secondoutput << "\n" ; // the output text file
});
}
secondoutput.close();
}
else cout << "Unable to open file";
return 0;
}
我可以要求帮助我吗?我想要一个输出文本文件,就像输出在屏幕上写的那样。看来最重要的事情是关于我放“ secondoutput << value << " ";
”和“ secondoutput << "\n" ;
”的地方。
我不知道他们应该在哪里。我总是将“ secondoutput << value << " ";
”放在其他代码中,它们运行良好,并给我一个输出文本文件。但是现在,我不知道为什么它们不起作用。提前感谢您的帮助
问候