Pages

Showing posts with label get input with scaanf() function. Show all posts
Showing posts with label get input with scaanf() function. Show all posts

Thursday, July 14, 2011

The scanf() Function in C and C++

Function name:  scanf()
Function Header: <stdio.h>
Declaration: int scanf (const char *format [, address,………..]);
Return Value:  On success, the scanf() function return the number of input fields successfully scanned, converted and stored.  Return 0, if no fields were stored

The scanf() function scans and formats input from stdin. It scans a series of input fields (all the characters up to the next white-space character) at a time. The format of scanf() function is scanf (“Formatted_specifier”, &variable_name). If you don’t use the & (Ampersand or Address Operator), you might get undesired result. So you should be careful to put it before the variable name. 


The list of formatted specifiers


Formatted Specifier
Meaning
%d
For storing integer value
%c
For storing a character
%s
For storing string
%f
For storing float and double value










Example of the scanf() function

#include<stdio.h>
#include<conio.h>

void main()
{
   int i;
   char c;
   char s[10];
   float f;

   clrscr();
   printf("Enter an integer number:");
   scanf("%d",&i);
   fflush(stdin);
   printf("Enter string:");
   scanf("%s",s);
   fflush(stdin);
   printf("Enter a floating number:");
   scanf("%f",&f);
   fflush(stdin);
  printf("Enter a character:");
  scanf("%c",&c);

   printf("\nYou have entered \n\n");
   printf("integer:%d \ncharacter:%c \nstring:%s \nfloat:%f",i,c,s,f);
   getch();
}

Here four formatted inputs are stored with scanf() function. There is no need to declare the address Operator (&) for storing string value because variable name is the original address for string value. The fflush(stdin) function is also being used to flush the buffer.
If you don't use fflush(stdin), there will be a problem in buffer and you can’t store inputs properly by scanf() function.

Output