C++:C++ Stdin Input: Mixing std::cin and std::getline Safely
C++•Stdin Parsing

C++ Stdin Input: Mixing std::cin and std::getline Safely

In Compilra GNU G++ 14 (C++17), all stdin is supplied upfront before clicking Run. A frequent C++ bug happens when std::cin >> leaves a newline behind right before std::getline(); consuming whitespace with std::ws fixes it reliably.

Syntax

std::cin >> count; std::cin >> std::ws; std::getline(std::cin, line);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
std::cin >> varistream&Reads whitespace-delimited tokens and leaves trailing newlines in the stream.
std::wsI/O ManipulatorDiscards leading whitespace (including leftover newlines) from std::cin.
std::getline(std::cin, str)istream&Reads a full line including internal spaces into a std::string.

Ready-to-Run Code Example

Executable in Compilra

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

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

int main() {
    int count = 0;
    if (!(std::cin >> count)) return 0;
    std::cin >> std::ws;

    for (int i = 1; i <= count; ++i) {
        std::string fullName;
        std::getline(std::cin, fullName);

        std::string scoresLine;
        std::getline(std::cin, scoresLine);
        std::istringstream iss(scoresLine);

        double score = 0.0, sum = 0.0;
        int n = 0;
        while (iss >> score) {
            sum += score;
            ++n;
        }

        double avg = n > 0 ? sum / n : 0.0;
        std::cout << "#" << i << " " << fullName
                  << ": avg = " << std::fixed << std::setprecision(1) << avg << "\n";
    }
    return 0;
}
Pre-Supplied Stdin (Input):
2
Ada Lovelace
95 98
Alan Turing
90 94 98
Expected Output:
#1 Ada Lovelace: avg = 96.5
#2 Alan Turing: avg = 94.0

How It Works: Step-by-Step

  • Lines 7-9: Reads the record count via std::cin and consumes the trailing newline with std::ws.
  • Lines 12-16: Uses std::getline for both the full name with spaces and the score line.
  • Lines 17-27: Parses variable-length scores via std::istringstream and formats the average.

Key Concepts

  • Provide all lines in the Standard Input (stdin) box before clicking Run; Compilra feeds the complete stdin buffer to the compiled binary.
  • std::cin >> std::ws is safer than std::cin.ignore() because it skips any trailing spaces or \r\n characters.
  • Using std::istringstream on a line from std::getline makes it easy to parse rows with unknown numbers of tokens.

Common Mistake: Calling std::getline immediately after std::cin >> n

The extraction operator stops right before the newline character, so the first std::getline reads an empty string instead of the next line.

❌ Incorrect
int n; std::string name;
std::cin >> n;
std::getline(std::cin, name); // Reads "" instead of name!
✅ Correct
int n; std::string name;
std::cin >> n >> std::ws;
std::getline(std::cin, name); // Reads full name line cleanly

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