简体   繁体   中英

C++ How to write a logfile

I have to write a program for school that calculates current, voltage, and efficiency. I have almost finished the program but now I want to write the results in a logfile. I have already read some threads but it didn't really help. here is the part that I want to write in a logfile:

cout<<"Die spannung U1 betraegt"<<U1<<"Ohm."<<endl;

I would really appreciate help thanks.

Simply using File I/O in C++ locally should solve your issue:

#include <fstream>
//...
ofstream fout("logfile.txt");
if (fout){
   fout << "Die spannung U1 betraegt" << U1 << "Ohm." <<endl;
   fout.close();
}

However, logging can become very cumbersome, so people have come up with all kinds of solutions for loggers. I found this article on logfiles (In context of the Singleton design pattern) to be very useful.

I would recommend using FILE and fprintf.

http://pic.dhe.ibm.com/infocenter/tpfhelp/current/index.jsp?topic=%2Fcom.ibm.ztpf-ztpfdf.doc_put.cur%2Fgtpc2%2Fcpp_fprintf-printf-sprintf.html

Remember - if you have threads - you need to protect the object,
don't forget to fflush() when the content is meaningful, and to fclose when you're done.

There are other methods to do it- I presonally like the bare bone the most..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM