User Input
To read user input in C, you can use the scanf function provided in the standard library. The scanf function allows you to read data from the standard input (usually the keyboard) and store it in variables.
Here is an example of using scanf to read an integer from the user in a C program:
#include <stdio.h>
int main()
{
int a;
printf("Enter an integer: ");
scanf("%d", &a);
printf("You entered: %d\n", a);
return 0;
}
In this example, we have declared a variable a to store the integer input from the user. The printf function is used to prompt the user to enter an integer, and the scanf function is used to read the integer from the standard input. The %d specifier in the scanf format string indicates that an integer is expected. The address of the variable a is passed as the argument to scanf, so that the value read from the input can be stored in the variable.
After the scanf function is executed, the value of a will be the integer entered by the user. The printf function is then used to print the value of a to the console.
You can use similar syntax to read other data types from the user, such as floating-point numbers, characters, and strings. For example:
#include <stdio.h>
int main()
{
float b;
char c;
char str[20];
printf("Enter a floating-point number: ");
scanf("%f", &b);
printf("You entered: %f\n", b);
printf("Enter a character: ");
scanf(" %c", &c);
printf("You entered: %c\n", c);
printf("Enter a string: ");
scanf("%s", str);
printf("You entered: %s\n", str);
return 0;
}
In this example, we have read a floating-point number, a character, and a string from the user using the scanf function.