C Scanf Function [1.0.8]

Posted by Parth Makadiya on 07:15 with No comments


 C scanf() function:
How to scan value from User at C Program ?

-The answer is scanf function
  • 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 printf() and 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. It is the Pointer we will see it later .

    Next C Post