Console Input and Output: printf() and scanf(), Explained

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

← Using the math.h LibraryNext lesson: Building Your First C Program →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
Width is the minimum number of characters a value takes, and precision, after a dot, is how many digits follow the decimal point for %f. In %6.1f, the value fills at least six characters with one decimal. A minus sign, as in %-8s, left-aligns the value, and a leading zero, as in %05d, pads with zeros, so 42 prints as 00042.
Why does scanf need an ampersand before a variable?
scanf needs the ampersand because it must store a value in the variable, so it needs the variable's address rather than a copy of its value. The & operator means address of. Without it, scanf receives the variable's current value where an address belongs, which is undefined behavior and often crashes the program. Clang warns that the format expects an int pointer but the argument is an int.
Why does scanf with %c read a newline instead of waiting?
scanf with %c often reads the newline left in the input buffer by an earlier entry. When a user types 3 and presses Enter, %d takes the 3 but leaves the newline, character code 10. Number conversions and %s skip leading whitespace, but %c reads exactly one character, whatever it is. A space before it, as in scanf(" %c", &answer), skips any whitespace first.
How do you read a double with scanf?
Read a double with %lf in scanf, as in scanf("%lf", &price), even though printf can print a double with %f. scanf must know the exact type of the variable it writes into, and %f in scanf means a float. To print the value with two decimals, use %.2f. A mismatched specifier is undefined behavior, so compiling with warnings helps catch it.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

Programming in C
3 credits · NCCRS
Enroll →