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
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: Workshop: Searching, Sorting, and Aggregating Arrays →← Standard String Library FunctionsNext lesson: Workshop: Searching, Sorting, and Aggregating Arrays →
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.
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 Input Validation and Formatted Output in C
What does scanf return in C?
How do you clear the input buffer after scanf fails in C?
How do you read a full line with spaces in C?
How do you line up columns with printf in C?
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 →