Capturing Input and Printing Results | C++ Programming

UPI Study › Courses › C++ Programming › Free lessons › Lesson 3.4 Free with a free account

Capturing Input and Printing Results

C++ Programming · Chapter 3: Program Design and the Object ModelSection 3.4 · lesson 19 of 84video coming soon

← Object-Oriented Principles in C++Next lesson: Planning and Scoping Your First Project →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

In this lesson

Two-way communication with the keyboard.

  • Read typed values into variables
  • Apply the prompt, read, confirm pattern
  • Predict exactly what an extraction consumes
  • Mix getline with extraction without surprises

Transcript

Everything said in the video, section by section (1,201 words). Read along, or search it.

Opening Idea

Why Programs Need Input

A program that only prints has one thing to say, and it says it identically, forever. The moment it can be told something, the same instructions can produce a different answer every time. This lesson covers how values get in from the keyboard, what reading actually does with the characters typed, and the one situation that surprises almost everybody.

Core Concept

Arrows Show Which Way Values Flow

Printing uses std c out, with two left-pointing arrows. Reading uses std c in, with two right-pointing arrows. They're deliberate mirror images. The arrows are the mnemonic: values flow the way they point. C in sends characters from the keyboard into total. C out sends total's value toward the screen. Both are streams. A stream is a sequence of characters flowing one way, and std c in is connected to whatever the person types. Because a stream is a sequence, not a snapshot, position matters. Every read starts exactly where the last one stopped. That one fact explains everything in this lesson.

Best Practice

Prompt, Read, Then Confirm

A read on its own produces a program that seems to have stopped. The cursor just sits there: is it waiting, calculating, or broken? So a read is always written as three steps. First, a prompt: how many items? Second, the read itself, into quantity. Third, a confirmation that prints back what was actually stored. Skip the prompt, and the program looks frozen. Skip the confirmation, and a wrong result later gives no way to tell, whether the reading or the arithmetic was at fault. And end a prompt with a space, not a newline, so the answer appears beside the question.

Definition

The Three-Part Extraction Procedure

The extraction operator doesn't just read what the person typed. It's a precise three-part procedure. First, skip any leading whitespace: spaces, tabs and newlines in front are discarded, however many there are. Second, read characters for as long as they can belong to the target type. An int takes digits and a sign. A string takes any non-whitespace characters. Third, stop at the first character that can't belong, and leave it in the stream. It isn't consumed. It's the first thing the next read will meet.

Consequence

Strings Read Only One Word

So whitespace separates one value from the next, and is never part of one. That catches everyone once. Reading into a string gives you one word, not a whole name. Type Anand Rao, and name holds Anand. Rao stays in the stream, and the next read anywhere picks it up, without anyone typing. That's why a later prompt sometimes seems skipped entirely.

Worked Example

Tracing Two Numbers Through the Stream

Here's that procedure on one line of input: two spaces, then 42, a space, 17, and the newline that Enter produces. C in, into a: the two leading spaces are skipped, and the four and two are taken. A is now 42. The read stops at the space after it. Then c in, into b: that one space is skipped, and the one and seven are taken. B is now 17. And notice what's still sitting at the end: the newline from Enter. Nothing has consumed it. Remember that, because it matters shortly.

Variations

Chained Reads and Stray Enters

Extractions chain, just like insertions. Each one in turn skips whitespace, takes what it can, and stops. Type 8, space, 5, and Enter: a is 8, b is 5, and only the newline is left. Type 8, Enter, 5, Enter, and you get exactly the same. The first Enter was just whitespace, skipped by the second extraction. Type 8, 5, 9, and the 9 stays waiting in the stream for the next read. And type only 8, then Enter, and the program appears to hang. The second extraction is still patiently skipping whitespace, waiting for something that can begin a number.

Alternative Tool

Getline for Text With Spaces

When a value genuinely contains spaces, like a full name, an address or a sentence, extraction is the wrong tool, because it stops at the first space by design. Use getline, which reads everything up to the next newline. It takes the stream first, and the string to fill second. No arrows at all. It consumes the newline that ended the line, but doesn't store it. And it doesn't skip leading whitespace, so leading spaces are kept. Use extraction for numbers and single words. Use getline for anything that may contain spaces.

Quick Check

Age Then Name: The Vanishing Prompt

Now put the two together, in the obvious order. The program asks for an age and reads it with c in, then asks for a full name, and reads it with getline. The person types 27, and presses Enter. Quick check: what happens next? Pause, and predict. The extraction takes the two digits, and stops at the newline, leaving it in the stream. Then getline reads up to the next newline, and the very first character it meets is that newline. So it stops at once, and stores an empty string. On screen, the second prompt appears and vanishes in the same instant, with no chance to type. It looks like a fault in the language. It isn't: it follows from the two rules.

The Fix

Discarding the Newline With Ignore

The remedy is to throw the leftover newline away before calling getline. That's what ignore does: it discards characters, up to and including the one you name. Read it as a sentence: discard characters, as many as it takes, until a newline has been thrown away too. The long expression in the middle just means no practical limit. Now getline waits properly, and reads the name. The greeting prints with both values, exactly as intended.

Rule of Thumb

Extraction Followed by Getline Is Risky

Here's the rule of thumb. The trouble only goes one way. Two extractions in a row are fine, because the second skips the newline as whitespace. Two getlines are fine, because each consumes its own. So whenever you write an extraction and then a getline, expect to discard the newline between them.

Bad Input

When Typed Characters Don't Fit

Everything so far assumed the characters typed suit the variable. When they don't, the behavior is worth knowing now. Type 12 a b c, and quantity is still 12. Reading stopped at the first letter, leaving a b c in the stream. Type 3.9, and quantity is 3. The dot can't belong to a whole number, so point nine stays behind. But type a b c, and the extraction finds nothing that could begin a number. It consumes nothing, sets quantity to zero, and marks the stream as failed.

Common Symptom

The Sticky Failed Stream State

That failed mark is sticky. Every later extraction on the stream does nothing at all, immediately, without waiting. So here's the symptom to recognize. A program that suddenly races to the end, printing every remaining prompt without pausing, and reporting zeros, has almost certainly failed an earlier read. Nothing crashes. Detecting and clearing that state comes later, with input validation.

Key Takeaways

Reading, Printing, and Leftover Newlines

To summarize. C in, with right-pointing arrows, pulls characters into a variable. C out, with left-pointing arrows, pushes values to the screen. Never write a read on its own: prompt, read, then confirm what was actually stored. Extraction skips leading whitespace, takes what fits the type, and leaves everything else in the stream, including the newline. So after an extraction, ignore the leftover newline before calling getline.

Think About It

Why Echo Back the Stored Value

Here's something to think about. Why is printing the value back worth doing, when the person just typed it themselves? Think about what happens when someone types 3.9, or 12 a b c, into a whole-number variable.

About C++ Programming at UPI Study

C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. 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.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
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

C++ Programming 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 Capturing Input and Printing Results

Why does getline skip my input after I use cin >> in C++?
The extraction operator leaves the newline from Enter in the input stream, and getline then reads up to that newline immediately. It finds an empty line, stores an empty string, and the prompt seems skipped. Discarding the leftover newline before calling getline fixes it.
How do I fix the leftover newline problem between cin and getline?
Call cin.ignore after the extraction and before getline. The call cin.ignore(numeric_limits<streamsize>::max(), '\n') discards characters up to and including the next newline, with no practical limit on how many. Include the limits header for numeric_limits. Afterward, getline waits for a fresh line and reads the full name.
What exactly does cin >> consume when it reads an int?
It skips any leading whitespace, reads characters that can belong to an int, and stops at the first character that cannot, leaving it in the stream. If the input is 12 a b c, the int is 12 and a b c remains. If it is 3.9, the int is 3 and .9 remains.
Why does cin >> name only read the first word of a full name?
Extraction into a string stops at whitespace, so typing Anand Rao stores only Anand. Rao stays in the stream, and the next read picks it up without any typing. To read a whole line with spaces, use getline(cin, name), which reads everything up to the newline.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) 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 C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 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 C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 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 C++ Programming.

84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

C++ Programming
3 credits · NCCRS
Enroll →