log like printf c++
To log messages in C++, you can use the printf
function from the C standard library. Here's an example of how to use printf
in C++:
#include <cstdio>
int main() {
int number = 42;
printf("The number is: %d\n", number);
return 0;
}
Explanation:
The
#include <cstdio>
line includes the header filecstdio
, which contains the declaration for theprintf
function.The
int main()
function is the entry point of the program.Inside the
main
function, we declare anint
variable namednumber
and assign it the value42
.The
printf
function is used to print the message "The number is: " followed by the value of thenumber
variable. The%d
format specifier is used to print the value of anint
variable.The
\n
is an escape sequence that represents a newline character, which adds a line break after the message is printed.The
return 0
statement indicates that the program has executed successfully, and the value0
is returned to the operating system.
Note: The printf
function is a C-style function, and although it can be used in C++, there are more modern and type-safe alternatives available in C++ for logging, such as std::cout
from the <iostream>
header or the logging libraries like spdlog
or glog
.