scanf


Though scanf and printf are the functions of legacy C language, these functions are being used extensively even in C++ programs. The programmers who have grown from C to C++ still have the obsession towards C functions like this. This print explains how to use the scanf functions for achieving basic functionalities, whether C or C++.

scanf  – C++ Tutorial:

The scanf() function is used to read the data from the standard input console. It waits till the data is entered and a return key is pressed. Once the “Enter” key is pressed, it returns and loads the variables with the input data read from the console. The format of the scanf function is as follows.

int scanf(const char* format_specifier,arguments);

scanf Arguments:

format_specifier : This is a string specifying the type and format of the data being read. There are several different formats available. These formats always start with a ‘%’ character. Some of the formats are specified as below.

The prototype for specifying the formats are : %[*][width][modifiers]type

The * specifies that the data is read but ignored. type is the type of data as specified by the format. The following table in this C++ Tutorial on scanf lists the types and the specifiers.

 

%c  Single character to be read
%d  Integer type to be read
%f  floating point
%s  character array to be read
%x  Hexadecimal data to be read

Sample code for using scanf – - C++ Tutorial:


#include <stdio.h>

void main()
{
int intData;
char chrData;
char strData[100];
float fltData;

printf(" C++ Tutorial - Enter the integer data :");
scanf("%d",&intData);
printf(" C++ Tutorial - Enter the Character data :");
scanf("%c",&chrData);
printf(" C++ Tutorial - Enter the string data :");
scanf("%s",strData);
printf(" C++ Tutorial - Enter the float data :");
scanf("%f",&fltData);

printf("C++ Tutorial nInteger Value: %dnChar: %cnString: %snFloat: %fn",intData,chrData,strData,fltData);

}

scanf returns the count of characters read during the operation. The return value is of type integer.