The problem is each loop I want to open a different file. I thought the simplest approach would have been to choose a string based on some if statements and pass it to the filename. However, this doesn't work. Presumably the headers dont support each other.
What is the simplest way to do this instead? Without having to rewrite the entire ofstream section multiple times in each for loop?
For example, perhaps I want to sequentially change the title. Then on the first loop it exports to "data1.txt", then "data2.txt" etc.
Also, as a side question, is it possible to re-open a file you have already written to and add more text without clearing text already in there?
std::string names[3] = {"file.1", "file.2", "file.3"};
for(constauto& s: names) {
std::ofstream out(s);
for(int i = 0; i < 10; ++i)
out << i << '\n';
}
it possible to re-open a file you have already written to and add more text without clearing text already in there?
Yes. Open it in append (each write will be appended to the end) or in "at end" (will set write position at the end of file, but you can rewind it manually if so desired) mode:
> ss.str().c_str() It is undefined behavior. temporary string object you get after calling str()
> will be destroyed after calling c_str() but before ofstream open function is executed.
Not with a conforming implementation. ofs.open (ss.str().c_str()); is fine.
When an implementation introduces a temporary object of a class that has a non-trivial constructor, it shall ensure that a constructor is called for the temporary object. Similarly, the destructor shall be called for a temporary with a non-trivial destructor. Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. The value computations and side effects of destroying a temporary object are associated only with the full-expression, not with any specific subexpression.
There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. The first context is when a default constructor is called to initialize an element of an array. ...
The second context is when a reference is bound to a temporary ...
So temporary value returned by str() is guaranteed to be destroyed only after open() is finished? Didn't know that.
I was under impression that temporaries could be destroyed at any moment after all direct operations on it were finished, unless their lifetime is extended through const reference.
So it compiles, runs, but file is not created? Did you check if file is properly open in your code? Are you sure what executable working directory is? If not, replace relative path with absolute.