What is the difference between cout and printf in C++?
| Point | std::cout | printf | std::print (C++23) |
|---|---|---|---|
| Language | C++ | C | C++23 |
| Type safe | Yes | No | Yes |
| Format | Stream operators << | %d, %s codes | {} placeholders |
| Custom types | With operator<< | No | With std::formatter |
#include <cstdio>
#include <iostream>
#include <print>
int main() {
int n = 5;
double d = 2.5;
std::cout << "cout: " << n << " " << d << '\n';
std::printf("printf: %d %.1f\n", n, d);
std::println("print: {} {:.1f}", n, d);
}
Output
cout: 5 2.5
printf: 5 2.5
print: 5 2.5
With printf a wrong code like %s for an int compiles but can crash. See C++ Input and Output.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |