Reputation: 1587
I have to output quite a few variables to an ASCII file, here is an example of how I am doing it now:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("output.txt", ios_base::out);
int a = 1;
int b = 3;
int c = 3453;
double d = 5.3;
string e = "a";
double f = 231.09;
file << "\"a\":" << a << endl;
file << "\"b\":" << b << endl;
file << "\"c\":" << c << endl;
file << "\"d\":" << d << endl;
file << "\"e\":" << e << endl;
file << "\"f\":" << f << endl;
file.close();
return 0;
}
The format of the output in the ASCII-file is as shown above: The name of the variable followed by its value.
Question: Is there a way to automatize this process, say, within a loop so I don't have to type it manually and clutter up my files? I would expect such a solution requires:
{a, b, c, d, e, f}
i
creates the string file << ToString[element i] << element i << endl;
I'd be happy to get a hint on how to proceed professionally with this task. Is this even possible with C++?
Upvotes: 0
Views: 54
Reputation: 4011
There's no "professional" way to write file. In your case, if your variables are declared explicitly its fine to write them one by one.
If you have a container (e.g. std::vector or std::list) you could iterate through them and write them, e.g:
for(auto e : myVector) [
file << e << "\n";
}
If you want "efficiency" in some cases, if you are writing GBs of data, it might be better to write in large chunks (though I believe most fs and possibly even the file stream in C++ does this optimization anyway).
So instead of doing the loop above do:
file.write(myVector, myVector.size())
The one problem here is that your variables are obviously of different types. In which case if you wish to use the approach with the containers you'd have to convert them to a similar type first... e.g.:
myVecotr.push_back(std::to_string(yourVariable))
Or you could use a vector for type std::any and ignore the conversion (though I'm not sure calling .write would work in this case and also std::any might have a tiny bit of overhead).
Small note: fstream has a destructor that releases the file. So there's no need to call close() as long as you allocated it statically. So in your case if you remove the file.close() you would get the same behavior since file is destroyed when you exit the function.
Upvotes: 0
Reputation: 36401
You may use the stringify operator in defines to automate the printing process:
#define FORMAT(x) "\""#x"\": " << x
#include <iostream>
using namespace std;
int main() {
int i=666;
cout << FORMAT(i) << endl;
}
which will produces:
"i": 666
But you can't make a list of variables and iterate over it at least without some dirty meta-programming.
Upvotes: 3