The code inputs an int
, n
, which is the number of lines to follow. Then, on each line, the first number goes to array A
, the second to B
, and the third to C
. I then pass these 4 arguments to sub
which I have no control over (in an object file where I don't know the implementation). All I know is that it returns an int
.
What I do then is write n
, the three arrays, and the result of sub
into an output file. Pretty simple code.
This code works as expected, but I just want to see if there are any conventions I should be following (especially C++11) and ideas to consider for efficiency.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include "sub.h"
int main()
{
std::ifstream file;
file.open(...);
if (!file) {
std::cerr << "Error opening file." << std::endl;
return EXIT_FAILURE;
}
int n;
std::string firstLine;
getline(file, firstLine);
std::stringstream(firstLine) >> n;
int a,b,c;
std::vector<int> A1,B1,C1;
while (file >> a >> b >> c) {
A1.push_back(a);
B1.push_back(b);
C1.push_back(c);
}
file.close();
std::ofstream output;
output.open(...);
output << n << "\n";
size_t size = A1.size();
for (size_t i=0; i<size; ++i) {
output << A1[i] << " " << B1[i] << " " << C1[i] << std::endl;
}
//call sub method with pointer to beginning of vectors
//I have no control over sub method, its signature is (int, int*, int*, int*)
int n1 = sub(n, &A1[0], &B1[0], &C1[0]);
//output result and close file
output << n1;
output.close();
}
Example input:
0 1 2 <- This is A[0], B[0], C[0]
2 3 4 <- This is A[1], B[1], C[1]
4 5 6 <- This is A[2], B[2], C[2]
The range-based for
-loop would not work in this case. It would, however, if I printed all of A, B, or C on one line.