C User Input: scanf(), Address Operator (&), Buffer Pitfalls & fgets()
Welcome to Phase 3 (Part 1): C User Input, scanf(), Buffer Mechanics & fgets() Masterclass! Writing interactive software requires receiving runtime input from users via the keyboard (Standard Input: stdin). In C, the standard input function is scanf() (Scan Formatted). However, because C operates directly with memory addresses, using scanf() requires understanding pointers, the address-of operator (&), and the notorious stdin input buffer trap where leftover newline characters corrupt subsequent reads. In this comprehensive guide, you will master reading all data types, solving the buffer newline glitch, reading multi-word strings safely with fgets(), and validating user inputs.
In C, functions receive arguments by value (copy). Kani scanf() function user enter chesina value ni manam declare chesina variable lo Direct ga RAM Memory Address lo write cheyyali. Andhuke variable peru mundhu Address-of Operator (&) pass chesthamu:
int age; // Allocated at RAM address 0x2000 (currently Garbage value)
scanf("%d", &age); // User enters "21"
1. scanf() parses text "21" -> binary 21
2. scanf() takes address 0x2000 and writes 21 directly into that RAM slot!
RAM Address 0x2000: [ 21 ] <--- age is now safely updated!
⚠️ When is & NOT needed in scanf()?
Strings (character arrays, e.g. char name[50];) lo & pettakkarledu: scanf("%s", name);.
Why? C lo array name automatically memory lo unna first element address (&name[0]) ni represent chesthundi!
#include <stdio.h>
int main(void) {
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("Your age is %d\n", age);
return 0;
}
scanf() requires the matching format specifier for each data type:
| Data Type | scanf Format Specifier | Syntax Example | Crucial Notes |
|---|---|---|---|
int | %d | scanf("%d", &num); | Skips leading whitespaces/newlines automatically. |
float | %f | scanf("%f", &gpa); | Reads 32-bit single precision float. |
double | %lf (Long Float) | scanf("%lf", &price); | ⚠️ Must use %lf in scanf (using %f will corrupt memory!). |
char | %c | scanf(" %c", &grade); | ⚠️ Does NOT skip whitespace; leading space in " %c" is mandatory! |
char[] (Word) | %s | scanf("%s", name); | Reads single word; stops at first space or newline. |
⚠️ Why Does scanf("%c") Skip Input After scanf("%d")?
User keyboard meedha 25 type chesi ENTER press chesinappudu, stdin input buffer lo '2', '5', '\n' store avthayi.
1. scanf("%d", &age) కేవలం 25 ని read chesi '\n' ని buffer lo వదిలేస్తుంది.
2. Next line lo scanf("%c", &grade) call ayinappudu, adhi user input kosam wait cheyyakunda, buffer lo unna leftover '\n' ని read chesi skip aypothundhi!
✅ Solution 1: scanf(" %c", &grade); (Leading space pedithe whitespace/newline ignore avthundhi).
✅ Solution 2: Clear remaining buffer characters with: while((c = getchar()) != '\n' && c != EOF);
scanf("%s", str) is dangerous because it stops at spaces and causes Buffer Overflow crashes if input exceeds array size. Professional C developers use fgets():
#include <stdio.h>
#include <string.h>
int main(void) {
char fullName[50];
int rollNumber;
// 1. Reading multi-word line safely with fgets
printf("Enter your Full Name (with spaces): ");
fgets(fullName, sizeof(fullName), stdin);
// Remove trailing newline captured by fgets
fullName[strcspn(fullName, "\n")] = 0;
// 2. Robust Input Validation with scanf return value
printf("Enter your Roll Number: ");
if (scanf("%d", &rollNumber) != 1) {
printf("❌ Invalid Input! You must enter a numeric integer.\n");
return 1; // Exit with error code
}
printf("\n--- Student Card ---\n");
printf("Name: %s\n", fullName);
printf("Roll No: %d\n", rollNumber);
return 0;
}
Run this interactive user greeting program in our online C compiler:
#include <stdio.h>
int main(void) {
char name[30];
int luckyNumber;
printf("Enter your name: ");
scanf("%29s", name); // %29s limits max characters to prevent overflow
printf("Enter your lucky number: ");
scanf("%d", &luckyNumber);
printf("Namaste, %s! Your lucky number squared is %d.\n", name, luckyNumber * luckyNumber);
return 0;
}