C
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Arrays and Strings
-
Section 5: Pointers
-
Section 6: Memory Management
-
Section 7: Structures and Unions
-
Section 8: The Preprocessor and Build Process
-
Section 9: Standard Library: stdio.h
-
Section 10: Standard Library: stdlib.h
-
Section 11: Standard Library: string.h
-
Section 12: Standard Library: ctype.h and wctype.h
-
Section 13: Standard Library: math.h, complex.h, fenv.h, tgmath.h
-
Section 14: Standard Library: Type and Limit Headers
-
Section 15: Standard Library: Error Handling and Debugging
-
Section 16: Standard Library: Localization and Encoding
-
Section 17: Standard Library: time.h
-
Section 18: Standard Library: Concurrency (C11)
-
Section 19: POSIX and System Programming (unistd.h)
-
Section 20: More Data Structures
-
Section 21: Algorithms in C
-
Section 22: Bitwise Operations
-
Section 23: Command-Line Programs
-
Section 24: Debugging and Best Practices
-
Section 25: Compiler and Language Internals
-
Section 26: Embedded and Cross-Platform Considerations
-
Section 27: Networking Basics
-
Section 28: Practical Projects
-
Section 29: Interview Practice
-
Section 30: C23 Modern Features
-
Section 31: More Practice and Review
79: Formatted Input with scanf Family
Wait, why the ampersand (&) for some variables but not others?
This is probably the first thing that trips people up. When you use printf, you just pass the variable. But with scanf, you usually see that & symbol. Here is the deal: scanf doesn't just need to know the value of your variable; it needs to know where it lives in memory so it can go there and overwrite it with the new value.
Think of it as giving scanf the address to your house rather than a picture of your house. If you just pass the variable, you're passing a copy of the value, and scanf has no way to send the data back to your original variable. However, you'll notice that when you read into a string (a char array), you don't use the &. That's because in C, the name of an array already acts as a pointer to its first element. It's already an address.
int age;
char name[50];
// We need &age to tell scanf WHERE to put the integer
scanf("%d", &age);
// No & needed for name because 'name' is already the address of the array
scanf("%s", name);
Why is my program skipping my character input?
I've seen this a hundred times. You ask for an integer, then you ask for a single character, and the program just breezes right past the second scanf. It feels like a bug in the compiler, but it's actually just how the input buffer works.
When you type "25" and hit Enter, you aren't just sending "25" to your program. You're sending "25\n" (the newline character). scanf("%d", &age) grabs the 25, but it leaves that \n sitting right there in the buffer. When the next scanf("%c", &initial) runs, it sees that newline character, thinks "Great! A character!", and consumes it immediately. Your program didn't skip the input; it just read your Enter key as the input.
The easiest fix? Put a single space before the format specifier. A leading space in scanf tells C to skip any whitespace—including those pesky newlines—until it finds the first actual piece of data.
int age;
char initial;
scanf("%d", &age);
// The space before %c is the magic trick here
scanf(" %c", &initial);
How do I read a whole sentence instead of just one word?
If you use %s, scanf stops reading the moment it hits a space, tab, or newline. If your user enters "John Doe", %s only grabs "John". It's frustrating, but it's by design.
If you want to read a full line of text using the scanf family, you can use a "scanset." Instead of %s, you use %[^\n]. This basically tells C: "Read everything until you encounter a newline character." I usually pair this with a width limit to prevent buffer overflows, which is a classic C security nightmare.
char full_name[100];
printf("Enter your full name: ");
// Read up to 99 chars, or until a newline is hit
scanf(" %99[^\n]", full_name);
What happens if the user types "banana" when I asked for an integer?
If scanf expects a number but finds a letter, it doesn't crash—it just stops. It leaves the "banana" sitting in the input buffer and returns a value indicating that it failed to match the requested format. If you don't check this return value, your program will likely enter an infinite loop or proceed with garbage data in your variables.
scanf returns the number of items it successfully assigned. If you asked for one integer and it returns 0, you know the user messed up. I always recommend capturing this return value in a variable to validate the input before moving forward.
int age;
printf("Enter your age: ");
if (scanf("%d", &age) != 1) {
printf("That's not a number! Please try again.\n");
// In a real app, you'd clear the buffer here
} 📋 Practical Task
The RPG Character Creator Validator
Build a small program that collects data for a game character. Your program must prompt the user for the following three pieces of information in this specific order:
- Character Name: A string that can contain spaces (e.g., "Sir Alistair the Brave").
- Character Level: A positive integer.
- Character Class Initial: A single character (e.g., 'W' for Wizard, 'F' for Fighter).
Requirements:
- Use the
scanffamily for all inputs. - Ensure the "Class Initial" is not skipped by the trailing newline from the "Character Level" input.
- Check the return value of the "Character Level" input; if the user enters something that isn't a number, print "Invalid level entered" and terminate the program.
- Print a final summary line:
"Welcome, [Name]! Level [Level] [Initial] created."
There are no comments for now.