scanf


return to main index


#include <stdio.h>


The function scanf() reads a text from the console as a result of the user of a program being prompted for information.

int     age;
float   small_pi;
double  big_pi = 3.14159265358;
char    name[256];
 
/* reading a string */  
printf("Enter your first name: \n");
scanf("%s", name);
printf("You entered: %s\n\n", name);

/* reading an integer */  
printf("Enter your age in years: \n");
scanf("%d", &age);
printf("You are %d years old\n\n", age);
 
/* reading a fractional number as a float */  
printf("The approximate value of PI is 3.1. Enter a more accurate value ?\n\n");
scanf("%f", &small_pi);
printf("You entered: %f\n", small);
 
/* reading a fractional number as a double */  
printf("What is one divided by two ?\n");
scanf("%lf", &big);
printf("You entered: %f but a more accurate value is %f\n\n", big_pi);

In particular notice the scanf function must be given a pointer to a variable, hence, the use of the & - the address-of operator. However, since the name of a character array (str) is considered in 'C' to be a pointer to the first element of the char array it is not necessary to prefix a string variable with an ampersand.