Mastering C Textbook
Collecting User Input
To collect an input from the user you can use scanf. It works with 2 parts. The first is the format of the input you are collecting, and the second is where the value(s) is being stored. In this case, %d is being used to collect an integer from the user.
printf("Enter a number > ");
int num;
scanf("%d", &num); // The program will wait here for a user input
printf("You entered %d\n", num);OUTPUT:
Enter a number > 123
You entered 123NOTE: In certain text editors, consider adding the following snippet at the beginning of your file to suppress warnings related to the scanf function: #define _CRT_SECURE_NO_WARNINGS
Collecting Floats
You can use %f to collect a floating point number. (number with decimals)
printf("Enter a decimal number > ");
float myFloat;
scanf("%f", &myFloat);
printf("You entered %.4f\n", myFloat); // Set the display to 4 decimal placesOUTPUT:
Enter a decimal number > 3.14
You entered 3.14
For doubles you need to use %lf instead of %f
double myDouble;
scanf("%lf", &myDouble);Collecting Chars
Use %c to capture 1 character from the user.
printf("Enter a character > ");
char myChar;
scanf("%c", &myChar);
printf("You entered %c\n", myChar);Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 11 more lessons in Mastering C Textbook.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.