Вы находитесь на странице: 1из 2

Muhammad Ali

muhammadallee@gmail.com

C++ I/O for C Programmers


This handout explains how C++ Input/output (I/O) is done against the equivalent C-syntax. Both
methods are provided in a tabular format. First column tells about the C-Style input/output and the next
column tells about the equivalent C++ syntax to achieve the same.

Header File
C Way C++ Way

#include <iostream>
#include <stdio.h> // Note that there’s no ‘.h’ at the
//end. This is new (C++) style of
including header files.

using namespace std;


// using namespace std is not a header
file though but it helps in using
‘cout’ and ‘cin’.

Integer Input
C Way C++ Way

//Takes and integer value as input //Takes and integer value as input
//from the user and stores it in iVal. //from the user and stores it in iVal.
int iVal = 0; int iVal = 0;
scanf("%d", &iVal); cin >> iVal;

Integer Output
C Way C++ Way

//Prints an integer value (iVal) as //Prints an integer value (iVal) as


//output. //output.
int iVal = 10; int iVal = 10;
printf("%d", iVal); cout << iVal;

Float Input
C Way C++ Way

//Takes a float value as input from //Takes a float value as input from
//the user and stores it in fVal. //the user and stores it in fVal.
float fVal = 0; float fVal = 0;
scanf("%f", &fVal); cin >> fVal;

Page 1 of 2
Float Output
C Way C++ Way

//Prints a float value (fVal) as //Prints an integer value (iVal) as


//output. //output.
int fVal = 10.56; int fVal = 10.56;
printf("%f", fVal); cout << fVal;

Character Input
C Way C++ Way

//Takes a character value as input //Takes a character value as input


//from the user and stores it in cVal. //from the user and stores it in cVal.
char cVal = '\0'; // NULL char cVal = '\0'; // NULL
scanf("%c", &cVal); cin >> cVal;

Character Output
C Way C++ Way

//Prints a character value (cVal) as //Prints a character value (cVal) as


//output. //output.
char cVal = '\0'; // NULL char cVal = '\0'; // NULL
printf("%c", cVal); cout << cVal;

Character Array Input


C Way C++ Way

//Takes a character array (str) as //Prints a character array (str) as


//input from the user. //input from the user.
char str[80] = ""; char str[80] = "";
gets(str); cin.get(str, 80);
//Reads ‘atmost’ 79 characters (1
//reserved for NULL).

Character Array Output


C Way C++ Way

//Prints a character array (str) as //Prints an character array (str) as


//output. //output.
char str[80] = "This is a test."; char str[80] = "This is a test.";
puts(str); cout << str;

Page 2 of 2

Вам также может понравиться