scanf() – I/O Function

scanf() – I/O Function

How is “scanf()” used in C++?

Explanation

scanf() is an I/O function which is used to read the “stdin” stream to store the data in the variables pointed by the argument list. The function returns the number of items read on success, it can be zero if a matching failure occurs. If an input failure occurs before reading data could result in EOF.

Syntax:

int scanf(const char *format,..);

The following table lists the format specifiers used by the scanf().

In the above syntax in the format parameter the function discards the whitespace. All the non-whitespace characters except “%” are skipped, then the next character is read. The “%” indicates a format specifier. The following table lists the format specifier used with “scanf” function.

Type Description Argument
c Used to read a single character, if the width is more than 1 the function reads all the specified width of characters and stores them in successive locations of the array passed as argument. char *
d Represents a decimal integer that mey be preceeded with +/ – sign. int *
e,E,f,g,G Used to represent a floating point number containing a decimal point that may have a +/- sign with a e or E character. float *
o Specifies an octal value int *
s This format type is used to read string of characters until a whitespace is found. char *
u Unsigned decimal integer unsigned int *
x,X Represents a hexadecimal integer. int *

Example :

#include
int main ()
{
char stri [80];
int a;
printf (“Enter your name: “);
scanf (“%s”,stri);
printf (“Enter your age: “);
scanf (“%d”,&a);
printf (“You name is %s , age is %d.n”,stri,a);
return 0;
}

Result :

Enter your name: Alex
Enter your age: 21
You name is Alex , age is 21.

In the above syntax in the format parameter the function discards the whitespace. All the non-whitespace characters except “%” are skipped, then the next character is read. The “%” indicates a format specifier. The following table lists the format specifier used with “scanf” function.





Leave a Reply

Your email address will not be published. Required fields are marked *