Skip to content
C++ Better Explained
Go back
How to Read Multiple Inputs on One Line in C++

How to Read Multiple Inputs on One Line in C++

Short answer: chain >> for a known count, or read the line and parse it with a stringstream when the count is unknown.

std::cin >> a >> b >> c;                       // known count

std::string line;                              // unknown count
std::getline(std::cin, line);
std::istringstream ss(line);
int v;
while (ss >> v) values.push_back(v);

Reading a Known Number of Values

#include <iostream>

int main() {
    int a, b, c;
    std::cout << "Enter three numbers: ";
    std::cin >> a >> b >> c;

    std::cout << a + b + c << '\n';
}

Typing 1 2 3 and pressing Enter fills all three. So does typing each on its own line — >> skips over any whitespace, newlines included, so it cannot tell the difference. That is occasionally surprising but usually convenient.

Mixed types work the same way:

std::string name;
int age;
double height;
std::cin >> name >> age >> height;    // "Ana 30 1.72"

Note name stops at the first space, so this cannot read “Ana Maria”. For that you need getline — the distinction is covered in cin vs getline.

Reading an Unknown Number of Values

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

int main() {
    std::cout << "Enter numbers separated by spaces: ";
    std::string line;
    std::getline(std::cin, line);

    std::istringstream ss(line);
    std::vector<int> values;
    int v;
    while (ss >> v) {
        values.push_back(v);
    }

    std::cout << "Read " << values.size() << " values\n";
    int sum = 0;
    for (int x : values) sum += x;
    std::cout << "Sum: " << sum << '\n';
}

This is the pattern worth memorising. Reading the line first means the console buffer is fully consumed, and parsing happens on a string you control — so nothing is left behind to break later reads.

Learning C++ properly? The C++ Better Explained Ebook covers input, strings and the STL in plain English — 87 pages, just $19.

Reading Comma-Separated Values

#include <sstream>

std::string line = "12,34,56";
std::istringstream ss(line);
std::string field;
std::vector<int> values;

while (std::getline(ss, field, ',')) {
    values.push_back(std::stoi(field));
}

The three-argument getline splits on whatever delimiter you give it. If the fields might have spaces around them — 12, 34, 56trim each field before converting, or stoi will still work since it skips leading whitespace but stod on "34 " leaves the trailing space harmlessly.

This is the same technique used for reading a CSV file, just applied to one line instead of many.

Reading Until the User Stops

#include <iostream>
#include <vector>

int main() {
    std::vector<int> values;
    int v;

    std::cout << "Enter numbers (Ctrl+D / Ctrl+Z to finish):\n";
    while (std::cin >> v) {
        values.push_back(v);
    }

    std::cout << "Read " << values.size() << " values\n";
}

The loop ends when extraction fails — either at end of input or on non-numeric text. If you want to stop on a sentinel word instead:

std::string token;
while (std::cin >> token && token != "done") {
    values.push_back(std::stoi(token));
}

Reading a Fixed Count into a Vector

int n;
std::cin >> n;                       // how many follow

std::vector<int> values(n);
for (int i = 0; i < n; ++i) {
    std::cin >> values[i];
}

This is the standard competitive-programming input format. Note std::vector<int> values(n) creates n elements up front, so indexing is safe — using push_back on an empty vector would also work but reserves repeatedly.

The Leftover Newline Trap

If you mix the two styles, the newline bites:

int n;
std::cin >> n;                       // leaves '\n' in the buffer

std::string line;
std::getline(std::cin, line);        // reads the leftover newline — empty!

Fix it by discarding the rest of the line first:

#include <limits>
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

The full explanation is in cin.ignore and clearing the input buffer.

Validating as You Read

std::istringstream ss(line);
int v;
std::vector<int> values;

while (ss >> v) values.push_back(v);

if (!ss.eof()) {
    std::cout << "Warning: input contained something that is not a number\n";
}

After the loop, ss.eof() is true only if the whole line parsed cleanly. If parsing stopped early on junk, the stream is in a fail state instead. For a full retry loop, see input validation.

Quick Reference

SituationApproach
Known countcin >> a >> b >> c
Unknown count, spacesgetline + istringstream + while (ss >> v)
Comma-separatedgetline(ss, field, ',')
Until end of inputwhile (cin >> v)
Count given firstread n, then loop n times
Mixing >> and getlinecin.ignore(max, '\n') between them

Take Your C++ Further

If you want input handling and the rest of the fundamentals explained properly rather than pieced together, the C++ Better Explained Ebook covers it in plain English. Just $19.

👉 Get the C++ Better Explained Ebook — $19


📋

Free Download: The 10 Mistakes Every C++ Beginner Makes

A free 1-page checklist that shows the exact traps that slow down every C++ beginner — so you can avoid them from day one.

🔒 No spam. Unsubscribe anytime.


Share this post on:

Written by

Sahil Bora

Software Engineer. Author and creator of C++ Better Explained.


Previous Post
INT_MAX and INT_MIN in C++: The Maximum and Minimum int Value
Next Post
How to Sort a Map by Value in C++

Keep Learning