Input Validation and Formatted Output in C | Programming in C

UPI Study › Courses › Programming in C › Free lessons › Lesson 7.7 Free with a free account

Input Validation and Formatted Output in C

Programming in C · Chapter 7: Arrays, Strings, Input Validation, and Formatted OutputSection 7.7 · lesson 46 of 786 min · free with a free account

← Standard String Library FunctionsNext lesson: Workshop: Searching, Sorting, and Aggregating Arrays →

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

In this lesson

Checking scanf input, reading lines with fgets, and aligning printf output.

  • Use the return value of scanf to detect bad input and end of input
  • Write a validation loop that clears the input buffer and checks a range
  • Read a whole line with fgets and remove its newline with strcspn
  • Format aligned output with printf width, precision, minus, and zero flags

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 (807 words). Read along, or search it.

Opening Question

Players Who Type Banana or Minus Five

Ask a player how many tokens they want, and someone will type banana. Or minus five. Or five thousand. A program that trusts every answer breaks the first time a real person uses it. The cure has two halves. Check the data coming in, and shape the data going out, so it's easy to read.

Scanf's Return Value

One, Zero, or EOF

Every scanf returns a number: how many values it managed to fill in. Here, we print what it returns. Type forty, and scanf returns one: one number read. Type letters, and it can't make a number, so it returns zero. And tokens keeps whatever it held before, here zero. If the input has ended, scanf returns the special value EOF, which is minus one here. An empty file as input shows it. So the first guard of every careful program is checking that number.

The Input Buffer

Rejected Letters Stay Waiting

There's a catch. When scanf fails, the letters it didn't accept stay waiting in the input buffer, a small waiting line for typed characters. The next scanf sees the same letters, and fails again, forever. The fix: read and throw away characters, one at a time, until the end of the line.

Validation Loop

Check for a Number, Then the Range

Put the guards in a loop, which runs while no good answer has been given. Inside, two checks happen in order. First, did we get a number at all? Got not equal to one catches the word. The inner while reads one character at a time with getchar, until the newline or the end of input. That empties the buffer. Second, is the number in range? Tokens less than one, or more than a hundred, is refused. Only a good number sets valid to one, and gets out. Sam tests it: abc, then minus five, then two fifty, then forty. Each wrong answer gets its message, and only forty gets through.

Quick Check

Testing the Edges Zero and One Hundred

Quick check. Here's the same kiosk, written more compactly. Sam goes for the edges: he types zero, then a hundred. What's the last line the kiosk prints? Pause and predict. Buying 100 tokens. Zero is less than one, so it's refused, and the loop asks again. A hundred isn't more than a hundred, so it's in range: both ends, one and a hundred, are allowed.

Reading Whole Lines

Fgets and Removing Its Newline

Percent s stops at the first space, so it can't read Priya Sharma. The tool for whole lines is fgets: the array, its size, and stdin, the keyboard. It reads up to a newline, never more than size minus one characters, and always ends with the marker, so it can't overflow your array. With nothing to read, it returns NULL. One surprise: fgets keeps the newline from the Enter key. Priya Sharma has twelve characters, but the raw text has thirteen. Strcspn finds the box of the first newline, or the marker if there is none, and the program puts a marker there. Clean text: twelve.

Common Trap

Scanf Leaves a Newline Behind

Mixing scanf and fgets has a trap. After scanf reads twelve, the Enter key's newline is still waiting. The next fgets sees it first, and happily returns an empty line. The name has one character, that newline. Sam never got read. The fix is the getchar loop from before: clear the rest of the line after scanf. Now the name is Sam plus its newline: four characters.

Formatted Output

Width, Precision, Minus, and Zero

Clean output matters too. Between the percent sign and the letter, a number is a width: use at least that many columns, padded with spaces on the left. A minus sign flips it to left-aligned. A dot and a number is the precision: digits after the point. And a zero before the width pads with zeros. Run it. The prices line up, because every price takes exactly eight columns, so the decimal points fall in the same place. Percent zero five d turns forty-two into zero zero zero four two. And the brackets show percent five d padding on the left, and minus five on the right.

Quick Check

One Snack Row in Brackets

Quick check. One snack row in brackets: Soda, left-aligned in six, then two point five with width five and one decimal. What exactly prints between the brackets? Pause and predict. Soda, two spaces, the bar, then two spaces and two point five. The minus puts the name's padding after it. Numbers are right-aligned unless you ask otherwise, so the padding of two point five goes in front.

Story Resolved

Numbers Only, Please

Back at the kiosk. Sam once typed twelve, as a word, and the first version printed a price for zero tokens. Priya added the scanf check and the range loop. Now the kiosk says: numbers only, please. Try breaking it again, she said.

Key Takeaways

Check Input, Shape Output

To recap. Check what scanf returns: one, zero, or EOF. After a failure, throw the bad line away with getchar. Loop until the answer is a number, and in range. Read whole lines with fgets, and remove its newline with strcspn. And shape output with width, precision, minus, and zero.

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 Input Validation and Formatted Output in C

What does scanf return in C?
scanf returns how many values it successfully stored. With scanf("%d", &tokens), typing 40 returns 1, typing letters returns 0 and leaves tokens unchanged, and reaching the end of input returns EOF, a negative constant that is usually -1. Checking this number is the first step of input validation, for example treating any result other than 1 as input that is not a number.
How do you clear the input buffer after scanf fails in C?
Read and discard characters with getchar until you reach the newline or the end of input: int c; while ((c = getchar()) != '\n' && c != EOF) { }. When scanf fails, the characters it rejected stay in the input buffer, so the next scanf sees them and fails again, forever. The same loop also removes the newline that scanf leaves behind before a later fgets call.
How do you read a full line with spaces in C?
Use fgets(name, sizeof name, stdin). It reads up to and including the newline, stores at most size minus one characters, and adds the null terminator, so it cannot overflow the array. Unlike %s, it does not stop at spaces, so Priya Sharma is read whole. Because fgets keeps the newline, remove it with name[strcspn(name, "\n")] = '\0';. It returns NULL when there is nothing to read.
How do you line up columns with printf in C?
Put a width between the % sign and the conversion letter. %8.2f uses at least 8 columns with 2 digits after the decimal point, so prices line up on their decimal points. Output is right-aligned by default; a minus sign, as in %-6s, left-aligns and pads on the right. A zero before the width, as in %05d, pads with zeros, so 42 prints as 00042.

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 →