UPI Study › Courses › Programming in C › Free lessons › Lesson 3.5 Free with a free account
Console Input and Output: printf() and scanf()
Programming in C · Chapter 3: Data Types, Variables, Math Library, and Console I/OSection 3.5 · lesson 17 of 787 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Building Your First C Program →← Using the math.h LibraryNext lesson: Building Your First C Program →
In this lesson
Format output with printf and read input safely with scanf.
- Match printf format specifiers to the types of their values
- Use width, precision, minus and zero flags to format output
- Read values with scanf using addresses and the right specifiers
- Explain the leftover newline problem with %c and fix it with a space
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (868 words). Read along, or search it.
Opening Bug
A Question That Will Not Wait
Priya's game asks how many games to play, then asks: play again, yes or no? But the second question flies past without waiting. Sam types y anyway, and the game still ends. Nothing is wrong with the keyboard. The answer is in how printf and scanf handle text.
Format Specifiers
Holes Filled in Order
The first thing given to printf is the format string: the text to show, with format specifiers in it. A specifier starts with a percent sign. It's a hole that says: put a value here, shown this way. The values after the string fill the holes in order. The kind of hole must match the kind of value. Percent d for an int, percent f for a double, percent c for one character, and percent s for text. Percent l d is for a long, and percent u for an unsigned int. Two percent signs print one percent sign. Run it. Percent f shows six places, 3.500000. Percent point two f shows exactly two, 3.50.
Width and Precision
Padding, Alignment and Decimals
Between the percent sign and the letter you can add two numbers. The width is the smallest number of characters to use, padded with spaces. The precision, after a dot, is how many digits to show after the decimal point. A minus sign makes the field left-aligned, and a leading zero pads with zeros. Run it. Names are left-aligned in eight characters, and the numbers line up on the right. The last line pads 42 to five digits: 00042. Money always gets point two f, even for a round three, so the cents never go missing.
Common Mistake
A Double in an Int Hole
And match every code to its value. Here a double goes into a percent d hole. What it would print is undefined, so don't run it. Clang warns at build time: format specifies type int, but the argument has type double. It even suggests the fix: percent f.
Quick Check
Three Fields Between Brackets
Quick check. One printf, three holes, with brackets and bars to show the edges. Pi to five places, then seven, then five. What exactly does it print? Pause and predict. The first field is padded to five characters, with one decimal: two spaces, then 3.1. The seven is left-aligned in four, so the spaces come after it. And percent zero three d pads five with zeros in front: 005. Numbers are right-aligned unless you ask otherwise.
Reading Input
Scanf Needs the Variable's Address
Scanf works like printf in reverse. Its format string says what to expect, and it stores what the player types. Because it changes your variable, it needs to know where the variable lives. The ampersand means the address of: the box's location. Printf only needs a copy. A double is read with percent l f, though it's printed with percent f. A word is read with percent s, which stops at the first space. Adding 19 keeps it from overflowing the 20-place box. The player types three, 1.50, and Maya on one line. Each scanf skips the spaces, takes what it needs, and leaves the rest for the next. Scanf also returns how many items it read. A careful program checks that count, as lesson 7.7 will show. For now, we trust the typist.
Missing Ampersand
Passing a Value Instead of an Address
Forget the ampersand, and scanf gets the value inside games instead of its address. A program that runs this will most likely crash, so we only build it. Clang gives two warnings. Format specifies type int star, but the argument has type int. And games is uninitialized when used here, because a copy of an empty box is passed.
Input Buffer
The Leftover Newline
Now Priya's bug. When a player types three and presses Enter, the keyboard sends two characters: the three, and the newline from the Enter key. They wait in a holding area called the input buffer. Percent d reads the three and stops. The newline stays behind. Numbers and words don't care, because they skip leading spaces and newlines. But percent c reads exactly one character, whatever it is. Run it and type three. The second question never waits. The character it read has code 10: the newline.
The Fix
One Space Before Percent c
The fix is a single space in front of percent c. A space in a scanf format means: skip any whitespace first. Run it again. Type three, then y. This time it waits, and reads code 121, the letter y.
Quick Check
Reading y and Then Enter
Quick check. This program reads two characters, each with percent c. The player types y, then presses Enter. What does it print? Pause and predict. It prints 121 and 10. The first percent c takes y, code 121. The second takes the leftover newline, code 10. Zero would need a character with code zero, but only y and the newline were waiting. And 121 twice would need a second y.
Story Ending
The Game Waits Now
Back to Priya's game. Your percent c eats the Enter from the number before it, Sam said. One space in the format fixed it. Now the game waits for the answer.
Key Takeaways
Matching Codes and Skipping Newlines
To recap. Printf fills specifier holes in order, and each code must match its value. Width, precision, minus and zero shape the output. Scanf needs the address of each variable, so put an ampersand before the name, and read a double with percent l f. Numbers skip leftover newlines, but percent c doesn't. Put a space before it. That space is the whole trick.
About Programming in C at UPI Study
Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
Where the credit goes
Universities that work with NCCRS
Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Console Input and Output: printf() and scanf()
What do width and precision mean in a printf format?
Why does scanf need an ampersand before a variable?
Why does scanf with %c read a newline instead of waiting?
How do you read a double with scanf?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Programming in C.
78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →