User Input scanf and getchar in C

Learn how to get user input in C using scanf and getchar on Debian 12 using Vim. Includes practical examples and clear explanations to understand both methods.
User Input in C: Using scanf and getchar
Getting input from users is a fundamental skill in C programming. It lets your program interact with users dynamically rather than using fixed data. Two commonly used functions for input are scanf()
and getchar()
.
scanf() Function
scanf()
reads formatted input from the standard input (keyboard). It is ideal for reading integers, floats, characters, and strings. Example:
int age;
scanf(\\"%d\\", &age);
Here, %d
tells scanf()
to read an integer, and &age
passes the address of the variable to store the input.
getchar() Function
getchar()
reads a single character from the user. Unlike scanf()
, it is more low-level and does not require format specifiers.
char ch;
ch = getchar();
Complete Example
The following program demonstrates both scanf()
and getchar()
in action.
#include
int main()
int age;
char initial;
printf(\\"Enter your age: \\");
scanf(\\"%d\\", &age);
while(getchar() != '\
'); // clear input buffer
printf(\\"Enter the first letter of your name: \\");
initial = getchar();
printf(\\"You entered age %d and initial %c\\\
\\", age, initial);
return 0;
Step-by-Step Explanation
- scanf(\\"%d\\", &age): Gets an integer from user input and stores it in
age
. - getchar(): Captures the next typed character. We use it after a
scanf
to get another character without interference from leftover newlines. - while(getchar() != '\
'): This loop clears the newline character from the input buffer so
getchar
works correctly.
Running the Program
Use the following commands in Debian 12 to compile and run:
gcc input.c -o input
./input
Expected Output
Enter your age: 25
Enter the first letter of your name: J
You entered age 25 and initial J
Conclusion
Understanding input functions like scanf
and getchar
is essential to write interactive programs. Practice using them in different ways to read various types of data effectively.
Subscribe to Our YouTube for More
https://blog.arashtad.com/updates/user-input-scanf-and-getchar-in-c/?feed_id=13598&_unique_id=689ee690ba72e
Comments
Post a Comment