C++:C++ Input and Output: std::cin, std::cout, and getline
C++•Input/Output

C++ Input and Output: std::cin, std::cout, and getline

Explore C++ stream I/O mechanisms from the <iostream> header, reading whitespace-separated values and full lines.

Syntax

std::cin >> variable; std::getline(std::cin, string_var);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
std::coutOutput StreamStandard output stream (stdout).
std::cinInput StreamStandard input stream (stdin).
std::getline()FunctionReads an entire line of text including spaces.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C++ locally:

#include <iostream>
#include <string>
#include <sstream>

int main() {
    // Simulating input stream via stringstream
    std::string simulatedInput = "Compilra Cloud\n8080";
    std::istringstream cinSimulation(simulatedInput);

    std::string serviceName;
    int portNumber;

    // Read full line including spaces
    std::getline(cinSimulation, serviceName);
    // Read formatted integer
    cinSimulation >> portNumber;

    std::cout << "Service Name: " << serviceName << "\n";
    std::cout << "Port Assigned: " << portNumber << "\n";

    return 0;
}
Expected Output:
Service Name: Compilra Cloud
Port Assigned: 8080

How It Works: Step-by-Step

  • Lines 7-8: Prepares an input stream containing line-based data.
  • Line 14: std::getline reads the entire string up to the newline.
  • Line 16: cin >> reads formatted data types directly.

Key Concepts

  • std::cin >> stops reading at whitespace (space, tab, newline).
  • std::getline(std::cin, str) reads an entire line including spaces.
  • Use std::endl only when flushing the buffer is required; otherwise prefer "\n".

Common Mistake: Mixing std::cin >> with std::getline() without clearing the trailing newline

cin >> leaves the trailing newline in the buffer, causing the subsequent getline() to read an empty line.

❌ Incorrect
int id; std::string name;
std::cin >> id;
std::getline(std::cin, name); // Reads empty newline!
✅ Correct
std::cin >> id;
std::cin.ignore(); // Clears newline
std::getline(std::cin, name);

Related C++ Tutorials & Compiler

Run and test C++ on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C++ Online Compiler