write to file function - combining text and variables?

I will be writing to a log file quite often and wanted to create an easy to use function to do so. The below works fine, however, my goal is to be able to do something such as writeLog("user text here " variable " more text"); if you get what I mean.

For example, in js you can do something like 'some text '+variable+' more text'. Is anything like that possible here when using ofstream in this use case?

1
2
3
4
5
6
7
8
	void writeLog(std::string logtext) {
		std::ofstream logfile;
		logfile.open("log.txt", std::ofstream::app);

		logfile << logtext;

		logfile.close();
	}
in js you can do something like 'some text '+variable+' more text'. Is anything like that possible here when using ofstream in this use case?

Yes. Just replace "+" with "<<":
logStream << "some text " << variable << " some more text" << endl;

So rather than having a writeLog() function, create a logStream object.
I don't think we are talking about the same thing... in the function I wrote I am passing what I want to be written into the file.

Basically, what I'd 'like' to do is writeLog("some text" << variable << "more text blah blah"); where the function receives it as logtext and appends it to the file.
Last edited on
I understand what you want to do. I'm saying that using a function is the hard way. You're better off just creating a log stream and writing to it directly. The effect is the same, as long as you use endl to finish lines instead of '\n'. The difference there is that with '\n', the data might not get flushed to the file so if the program crashes, it will be missing the some of the data.

If your real intention is to have writeLog() do more stuff then consider writing your own streambuf class and put the extra processing in there.
Topic archived. No new replies allowed.