C TutorialLesson 20Free preview
C User Input
This lesson is part of C · All levels
Summary
The program can receive input from the user through the scanf function of the stdio.h header, which reads data from the stdin according to the specifier format. For ordinary variables, scanf requires the & (memory address) mark to write values into it, except for char arrays that are sufficiently written by name only. Input spaces or new lines have their own rules so choosing the right function (scanf, fgets, or getchar) is important. Always validate the scanf results to ensure the input is fully received.
Key points
- Scanf("%d", &x) read the value according to the format and then save it to the x address
- Sign & required for regular variables, but not for char arrays
- The number and order of arguments must be in accordance with the specifier format
- Returns the number of items that have been read successfully, useful for validating input
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.