Concepts / Input and Output Streams in C++

Input and Output Streams in C++

The >> operator reads input into a variable, and the variable's type determines what input is accepted.

  • Programming

A Question That Needs Two Answers

Many programs need to pause and ask a person a question that has only two sensible answers. Examples include whether to continue, whether to save changes, or whether to delete a file. A program that asks such a question has to do two things: collect the reply the person types, and then branch on that reply so the rest of the program behaves differently depending on what was typed.

This article starts with one small function that does exactly that. Read the function first and try to decide what it gives back before reading the explanations. The reasoning you do at that moment is the skill this article is building. The function has no loop and no second question. It reads a single character, makes one comparison, and leaves.

Reading the Function Before Explaining It

Code walkthrough
bool askToProceed() {
    cout << "Do you want to proceed (y or n)?\n";
    char answer = 0;
    cin >> answer;
    if (answer == 'y')
        return true;
    return false;
}
  1. 1
    Line 2 prints the question. The \n at the end moves the cursor to a new line, so the typed reply appears on a fresh line.
  2. 2
    Line 3 declares answer as a char and gives it the starting value 0, so it has a defined value before any input arrives.
  3. 3
    Line 4 reads one character from the standard input stream cin into answer.
  4. 4
    Line 5 compares the stored character with the lowercase letter y. The double equals sign is the comparison.
  5. 5
    Line 6 runs only when the comparison is true. It returns true and the function ends immediately.
  6. 6
    Line 7 runs only when the comparison was false. It returns false.
  • The function name askToProceed is used here only for reference; the body is the part that matters.
  • The question is printed with the output operator <<.
  • The variable answer is declared on the line just before it is read.
  • The >> operator reads one reply into answer.
  • The if statement tests whether answer holds the character y.
  • The second return runs only when the first one was skipped.

What do you think happens?

The user types n and presses Enter. What does askToProceed return?

  • true

  • false

Reveal answer
Answer:

false

The stored character is n, so answer == 'y' is false. The if body is skipped, and execution reaches return false.

How >> Pulls a Character In

The >> operator is used for input. Its name is pronounced 'get from', and it is the mirror image of the << output operator, which is pronounced 'put to'. Where << pushes a value toward the screen, >> pulls a value in from an input stream. The standard input stream is called cin, so the expression cin >> answer asks the program to take what the user typed and store it in answer.

In the statement cin >> answer, cin is the stream the data comes from, >> is the operator that moves the data, and answer is the destination variable. The right-hand side of >> is the target of the input. The diagram below traces where the typed character travels.

Typed replyy, then Enter pressedcin streamstandard input>> operatorget fromanswerchar variabletyped inputread from streamstored in
When the user types y and presses Enter, where does that character travel, and in what order does it reach the variable?

The operator itself does not decide what counts as valid input. The declared type of the receiving variable does. Because answer is a char, the input operation reads a single character. If the target were declared as a different type, the same >> operator would accept a different kind of input.

Why the Declaration Sits Next to the Read

A declaration can appear anywhere a statement can, so the programmer does not have to gather every variable at the top of the function. The variable's definition sits at the point where the program first needs it. In this function, the declaration char answer = 0; comes after the question is printed and right before the read. This keeps the three steps of asking, declaring, and reading close together in the code.

The type char means the variable holds one character. The initial value 0 gives the variable a defined starting value before any input arrives. The type is what sets the rules for the input, so reading the declaration is the first step in predicting what the function will accept.

Choosing a Return Value with if

An if statement tests a condition and runs a statement only when that condition holds. The general form is if (condition) statement. In this function the condition is answer == 'y'. When the condition is true, the return true statement runs and the function ends. When the condition is false, the if statement does nothing, and execution continues to the line after it, which is return false.

answer == 'y'?compare stored characterreturn truefunction endsreturn falsereached when the if wasskippedtruefalse
Given the stored character, which branch of the if statement runs, and which value does the function send back to its caller?

What do you think happens?

The user types Y with a capital letter. What does askToProceed return?

  • true

  • false

Reveal answer
Answer:

false

The condition tests for the lowercase letter y. The source states that the function returns false for every reply other than y, so the capital Y also produces false.

Tracing a Result That Surprised a Teammate

Suppose a teammate says the function is broken because it returned false even though the person clearly meant yes. Instead of guessing, walk through the code in order and check each step against what the programmer intended. Find the first place where the actual state stops matching the expected state.

Worked example

Locating the line where the result diverged

The user meant yes but typed Y with a capital letter. The function returned false. Find the line where the result first diverged from the expected yes.

  1. 1
    Print the question

    The question appears and the cursor moves to a new line, so the reply will land on a fresh line.

  2. 2
    Declare answer

    answer is a char starting at 0. Nothing has been read yet, so no divergence has occurred.

  3. 3
    Read the reply

    cin >> answer stores the character Y in answer. The stored value is capital Y, which is what the user typed.

  4. 4
    Compare with y

    The expected state here was a match for yes. The actual comparison is answer == 'y', and capital Y does not equal lowercase y, so the condition is false. This is the first line where the actual state differs from the expected one.

  5. 5
    Return false

    The skipped if leads to return false. This value is a consequence of the divergence at the comparison, not the original cause.

Result

The divergence is at the comparison line. The function behaved as written: it tests for lowercase y, and the stored character was capital Y. The question to ask is whether the test matches what the program means by yes.

The same method works for any unexpected result. Read the code in the order it executes, write down the value each line leaves behind, and compare each value with what you expected. The first line where your expectation and the actual value differ is the place to look.

Mistakes When Reading This Function

  • Common mistake

    Writing a single equals sign in the condition

    What it looks like
    if (answer = 'y')
    Why it fails

    A single equals sign assigns a value to answer instead of comparing it with y.

    Do this instead

    Use the double equals sign, as in if (answer == 'y'), so the stored character is tested.

  • Common mistake

    Treating false as a deliberate refusal

    Why it fails

    The function returns false for every reply other than y, including n. A false result therefore does not identify a deliberate no; a mistyped reply produces the same value.

    Do this instead

    Read the return value as meaning not y. If the caller must tell a refusal apart from a mistyped reply, the design needs to change.

  • Common mistake

    Assuming the >> operator decides which input is valid

    Why it fails

    The operator only moves data into the target. The declared type of the receiving variable determines what kind of input is accepted.

    Do this instead

    Check the declaration of the receiving variable when predicting what input will be accepted.

Practice Tracing the Function

EASY

Trace askToProceed for the reply y, and then for the reply n. For each reply, name the line where the behavior is decided and state the value the function returns.

Hints
  • Which line decides whether the if body runs?
  • A return inside the if ends the function before the next line runs.
  • Compare the stored character with 'y' exactly, including its case.

Key Takeaways

  • The >> operator reads input from a stream such as cin into a variable, and the variable's declared type determines what input is accepted.
  • An if statement runs its body only when the condition is true; a return statement ends the function immediately, so the second return runs only when the first was skipped.
  • The function returns false for every reply other than y, so a false result does not by itself distinguish a deliberate refusal from a mistyped reply.
  • When a result diverges from expectation, trace the code in execution order and find the first line where the actual value differs from the expected one.

Related concepts

More concepts starting with I