CodeTheRobot

C++ Beginner · Lesson 05 of 22

Input and output: std::cout, std::cin, streams

Printing, reading numbers, checking that input succeeded, and string streams.

Estimated time · 45–75 min

Learning goals

What you will understand

  • Explain input and output: std::cout, std::cin, streams in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

std::cout writes to standard output, std::cin reads from standard input, and std::cerr writes errors. The << operator sends values into a stream and >> extracts them. These are stream objects: the same operators also work on files and on std::stringstream.

Input can fail, for example when the user types letters where a number is expected. Always check the stream (if (std::cin >> value)) before using the value.

Guided lesson

Work through these steps

  1. 1.

    Read the input and output: std::cout, std::cin, streams example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

#include <iostream>
// Header that provides std::cout, std::cin and std::cerr.
#include <sstream>
// Header for std::istringstream, a stream that reads from a string.
double target{};
// Variable to receive the target angle (value-initialized to 0.0).
std::cout << "Target angle (deg): ";
// Print a prompt without a newline.
if (!(std::cin >> target)) {
// Try to read a number; the condition is true when reading failed.
  std::cerr << "not a number\n";
// Report the problem on the error stream.
  return 1;
// Leave main with a non-zero exit code, meaning failure.
}
// End of the failure branch.
std::istringstream line{"12.5 3"};
// A stream that reads from a string, handy for parsing and for tests.
int joint{}; double speed{}; line >> speed >> joint;
// Extract two values in order; a stream parses text into typed values.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Values in memory

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

motor speed030x1070x1410x1890x1c40x2060x2420x2880x2c*p += 10VALUES IN MEMORY

Demo for Input and output: std::cout, std::cin, streams. Expected result: joint 3 speed 12.5

Practice code

Now type it yourself

Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice

#include <iostream>
#include <sstream>

int main() {
  std::istringstream line{"12.5 3"};  // pretend this text was typed by a user
  double speed{};
  int joint{};
  // TODO: read speed then joint from line; if reading fails print "bad input" to std::cerr and return 1
  std::cout << "joint " << joint << " speed " << speed << '\n';
  return 0;
}

Expected output

joint 3 speed 12.5
Stuck? Show the full solution (try it yourself first)
#include <iostream>
#include <sstream>

int main() {
  std::istringstream line{"12.5 3"};  // pretend this text was typed by a user
  double speed{};
  int joint{};
  if (!(line >> speed >> joint)) {
    std::cerr << "bad input\n";
    return 1;
  }
  std::cout << "joint " << joint << " speed " << speed << '\n';
  return 0;
}

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Read a joint number and an angle from std::cin. Reject a non-number without crashing, print the result with std::cout, then parse the same input from a std::istringstream in a test.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.