What is the difference between printf() and cout in C++?

C++ProgrammingServer Side Programming

printf()

This is mainly used in C language. It is a formatting function that prints to the standard out. It prints to the console and takes a format specifier to print. It returns an integer value. It is not type safe in input parameters. It can be used in C++ language too.

Here is the syntax of printf() in C and C++ language,

printf(“string and format specifier”, variable_name);

Here,

  • String − Any text/message to print on console.

  • Format Specifier  − According to the variable datatype, use format specifiers like %d, %s etc.

  • variable_name  − Any name given to declare the variable.

Here is an example of printf() in C language,

Example

 Live Demo

#include<stdio.h>
int main() {
   int a = 24;
   printf("Welcome! \n");
   printf("The value of a : %d",a);
   getchar();
   return 0;
}

Output

Here is the output

Welcome!
The value of a : 24

cout

This is used in C++ language. It is an object of iostream in C++ language. It also prints to the console. It does not take any format specifier to print. It does not return anything. It is type safe in input parameters.

Output

Here is the syntax of cout in C++ language,

cout << “string” << variable_name << endl;

Here,

  • string − Any text/message to print on console.

  • variable_name − Any name given to the variable at the time of declaration.

Here is an example of cout in C++ language,

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int a = 28;

   cout<< "The value of a : " << a;
   printf("\nThe value of a : %d", a);
   
   return 0;
}

Output

Here is the output

The value of a : 28
The value of a : 28
raja
Published on 23-Oct-2018 13:58:26
Advertisements