Getting Terminal Input in C Program
Getting Input in C Program
In C programming scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards and store it in variables.
Example 1: Integer Input
#include <stdio.h>
int main()
{
int myInteger;
printf("Enter integer value: ");
scanf("%d", &myInteger);
printf("myInteger = %d \n", myInteger);
return 0;
}
Output:
Enter integer value: 10
myInteger = 10
- We have declared a variable
myIntegerto store integer type values. - We use
%dformat specifier insidescanf()to takeintinput from user - Notice, that we have used
&myIntegerinside scanf(). - THis is because, by using
&myIntegerwe are accessing the address ofmyInteger. - The value entered by the user is stored in that address.
Example 2: Float and Double Input
// Float and Double Input
#include <stdio.h>
int main()
{
float myFloat;
double myDouble;
printf("Enter a float number: ");
scanf("%f", &myFloat);
printf("Enter a double number: ");
scanf("%lf", &myDouble);
printf("myFloat = %f \n", myFloat);
printf("myFloat = %lf \n", myDouble);
return 0;
}
Output:
Enter a float number: 10.1
Enter a double number: 11.2
myFloat = 10.100000
myFloat = 11.200000
- We use
%fand%lfformat specifier forfloatanddoublerespectively
Example 3: Character Input
// Character Input
#include <stdio.h>
int main()
{
char myChar;
printf("Enter a character: ");
scanf("%c",&myChar);
printf("You entered: %c \n", myChar);
return 0;
}
Output:
Enter a character: a
You entered: a
- When a character is entered by the user in the above program, the character itself is not stored. Instead, an integer value
(ASCII value)is stored. - When we display that value using
%ctext format, the enteredcharacteris displayed. - If we use
%dto display the character, it'sASCII valueis printed.