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:
| Parameter | Type | Description |
|---|---|---|
| std::cout | Output Stream | Standard output stream (stdout). |
| std::cin | Input Stream | Standard input stream (stdin). |
| std::getline() | Function | Reads an entire line of text including spaces. |
Ready-to-Run Code Example
Executable in CompilraRun 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
C++ Stdin Input: Mixing std::cin and std::getline Safely
Combine formatted extraction (std::cin >>) with line-based std::getline() cleanly without skipping lines or leaving whitespace.
C++ Variables and Primitive Data Types with Examples
Learn how to declare typed variables in C++ including int, double, char, bool, and auto.
C++ std::string and std::string_view (C++17)
Master text manipulation with std::string and high-performance zero-copy std::string_view.
C++ Type Casting: static_cast and Modern C++ Casts
Master compile-time type conversion using static_cast and understand modern C++ casting operators.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.