The Programming Gurus

C scanf Function With Example


C scanf() function:
  • scanf() function is inbuilt library function in C which are available in C library by default. This function is declared and related macros are defined in “stdio.h” which is a header file.
  • scanf() function is used to read character, string, numeric data from keyboard.
  • Consider below example program where user enters a character. This value is assigned to the variable “ch” and then displayed.
  • Then, user enters a string and this value is assigned to the variable ”str” and then displayed.

Example program for scanf() functions in C:
#include <stdio.h>
int main()
{
char ch;
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}   
Output
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai       

  • The format specifier %d is used in scanf() statement. So that, the value entered is received as an integer and %s for string.
  • Ampersand is used before variable name “ch” in scanf() statement as &ch.
  • It is just like in a pointer which is used to point to the variable.
0 Comments For "C scanf Function With Example"

Back To Top