OnlineCBT Logo OnlineCBT
C++ · LESSON 2

C++ Program Structure & I/O Streams (cin / cout)

By Ratan Updated: 15 Oct 2026

Understand #include <iostream>, std namespace, cout insertion (<<), and cin extraction (>>).

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Use streams and check extraction

A small C++ console program includes the headers for the facilities it uses, defines main, reads values and reports a result. Input streams maintain a state that records whether an extraction succeeded. Never calculate with input that failed validation.

Worked program: total lesson time

#include 
int main() {
    int lessons = 0;
    int minutes = 0;
    std::cout << "Enter lesson count and minutes each: ";
    if (!(std::cin >> lessons >> minutes)) {
        std::cerr << "Expected two integers.\n";
        return 1;
    }
    if (lessons < 1 || lessons > 100 || minutes < 1 || minutes > 180) {
        std::cerr << "Values are outside the permitted range.\n";
        return 1;
    }
    std::cout << "Total minutes: " << lessons * minutes << '\n';
}

Input 4 30 produces Total minutes: 120. Input four 30 reports an extraction error. The range checks also keep multiplication small enough for the integer type. Reaching the end of main is equivalent to returning zero.

Strings containing spaces

std::cin >> name reads a whitespace-delimited word. std::getline(std::cin, name) reads a line and discards its delimiter. Mixing formatted extraction with getline often leaves the previous newline waiting in the stream. Handle that boundary deliberately.

#include 
#include 
// After a successful numeric extraction:
std::cin.ignore(std::numeric_limits::max(), '\n');
std::string full_name;
if (!std::getline(std::cin, full_name)) {
    // Handle end-of-file or an input error.
}

These are fragments to place inside a function with iostream included. ignore discards the remainder of the current line. Alternatively, read complete lines throughout and parse each line separately.

Recovering a failed stream

After a recoverable format failure in an interactive loop, clear the failure state, then discard the invalid line. Calling clear alone does not remove the bad input. End-of-file should normally end the loop instead of repeatedly prompting forever.

Output choices

Use cout for normal results and cerr for diagnostic messages. A newline character ends a line; std::endl also flushes the stream. Flushing every iteration can add unnecessary overhead. Include iomanip when formatting decimal precision with std::fixed and std::setprecision.

Practice

  1. Read a student's full name and print a greeting without losing spaces.
  2. Test empty input, letters where numbers are required, and the maximum permitted values.
  3. Why is extracting an int from the string "3.5" not enough to validate the entire line? It can consume the integer prefix and leave trailing characters; full-line validation needs additional checks.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat