To split a string by spaces in C++, read it into a std::istringstream and extract words with >>. This concise approach uses whitespace as the delimiter and automatically skips repeated spaces; if you need to preserve empty fields or split only on literal space characters, use a custom approach instead.
Split a string into words with a stream
Include <sstream> and <string>, then extract each word into a string. The stream stops at whitespace, which includes spaces, tabs, and newlines.
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string text = "C++ split string by space";
std::istringstream input(text);
std::string word;
while (input >> word) {
std::cout << word << '\n';
}
}
The output is one token per line: C++, split, string, and by, followed by space. This method is usually the clearest choice when “split” means separating ordinary words in user-entered or file text.
Store the results in a vector
If later code needs to access the pieces, append each extracted word to a std::vector<std::string>. Add <vector> to the includes:
std::string text = "red green blue";
std::istringstream input(text);
std::vector<std::string> words;
std::string word;
while (input >> word) {
words.push_back(word);
}
After this loop, words.size() is 3, and the elements are "red", "green", and "blue". A range-based loop can then process them:
for (const std::string& item : words) {
std::cout << item << '\n';
}
For numeric input, extraction can also parse values directly. For example, reading each item into an int works for a line such as "12 34 56", provided every token is a valid integer. If invalid tokens matter, read strings first and validate or parse them deliberately.
What counts as a space?
The stream extraction operator >> uses the stream’s whitespace rules, not just the ordinary space character. It treats sequences of whitespace as separators and discards leading and trailing whitespace. Thus, a string such as " one two\tthree " produces three words: one, two, and three.
This behavior is useful for natural-language-like input, but it is not the same as splitting on exactly one ASCII space. In particular, consecutive separators do not create empty tokens. If the input is "one two", stream extraction returns two words, not three elements with an empty item between them.
There is another character-encoding detail: in ordinary narrow strings, stream whitespace classification is based on the active C locale and character values. It is suitable for standard ASCII whitespace in typical input, but it is not a general Unicode word-segmentation algorithm. Text containing non-ASCII spacing characters may need an explicit Unicode-aware library or preprocessing suited to its encoding.
Split on a literal space with find
When the delimiter must be exactly the character ' ', use std::string::find and substr. This approach can preserve empty pieces caused by repeated spaces and can retain a trailing empty field:
#include <string>
#include <vector>
std::vector<std::string> splitOnSpace(const std::string& text) {
std::vector<std::string> parts;
std::size_t start = 0;
while (true) {
std::size_t end = text.find(' ', start);
if (end == std::string::npos) {
parts.push_back(text.substr(start));
break;
}
parts.push_back(text.substr(start, end - start));
start = end + 1;
}
return parts;
}
For "one two ", this function returns four elements: "one", "", "two", and "". That may be important when fields are positional, such as in a simple space-delimited format. If empty elements are unwanted, remove them afterward or adapt the loop to skip them. This function deliberately does not treat tabs or newlines as delimiters.
Choosing the right method
- Use
std::istringstreamfor words separated by one or more whitespace characters, especially when repeated spaces should behave like one separator. - Use
findandsubstrwhen the delimiter is specifically a literal space, or when empty fields and exact delimiter placement matter. - Use
std::getlinewith a delimiter when reading one field at a time from a stream and the delimiter is a single character. For example,std::getline(input, field, ' ')reads through the next literal space; unlike formatted extraction, consecutive spaces can yield empty fields.
These choices also affect performance and memory. A stream is readable and convenient, and is generally more than adequate for ordinary lines. A custom scan gives more control over the delimiter and token policy. Either way, a vector stores every result, so for very large input you can process tokens as they are found instead of retaining them all.
Common problems and input details
A frequent mistake is expecting std::getline with no delimiter argument to split words. Its default delimiter is a newline, so it reads a whole line, including spaces. To split that line into words, pass the resulting string to an std::istringstream, or use getline with a space delimiter when literal-space behavior is intended.
Another common issue occurs when mixing formatted input and line input. After std::cin >> number, the newline remains in the input stream. A following std::getline may consume that newline and appear to return an empty line. Use std::getline(std::cin >> std::ws, line) when leading whitespace should be discarded before reading the next line, or handle the leftover newline explicitly when it matters. Note that std::ws discards all leading whitespace, not just one newline.
For input from a file, check that opening and reading succeeded. An empty line naturally produces no words with stream extraction, while a literal-space splitter may return one empty field for an empty string depending on its design. Decide whether that distinction is meaningful for your data format.
Frequently Asked Questions
How do I split a string by spaces in C++?
Use std::istringstream and repeatedly extract into a std::string with input >> word. It splits on runs of whitespace and skips empty tokens.
Does stringstream split on multiple spaces?
Yes. Formatted extraction skips leading whitespace and consumes a word up to the next whitespace, so multiple spaces, tabs, or newlines do not create empty results.
How do I keep empty strings between spaces?
Do not use >> extraction for that requirement. Scan with find(' ') and substr, or use std::getline with ' ' as the delimiter, and verify how your chosen method handles a trailing delimiter.
Can I split a string without stringstream?
Yes. Use find and substr for explicit delimiter control, or write a character-by-character loop. For simple whitespace-separated words, however, a stream is often less code and easier to read.
Does std::getline split on spaces by default?
No. Its default delimiter is the newline character. Supply ' ' as the third argument to use a literal space, or read a line and extract words from it with a string stream.
Related
- Google Sheets Split String by Space: 3 Ways
- Excel Text to Columns: Split at the First Space
- How to Apply for CPP Split: Step-by-Step
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Apply Data Entry: Step-by-Step GuideData entry is the process of transferring information from one format (like paper forms, PDFs, or audio recordings)…
- GL Wand Excel Not Responding: Causes and Fixes to TryIf GL Wand makes Excel show “Not Responding,” first stop clicking and give the current operation a little…
- How to Insert a Line Between Rows in Microsoft WordTo add a horizontal line between rows in a Word table, click inside the table, select the table…
- How to Email an Excel File That’s Too Large SafelyThe most reliable way to email an Excel file that exceeds an attachment limit is to upload it…
- Data Entry Executive: Role, Skills, and Career FactsA data entry executive is a professional who inputs, updates, and maintains information in computer systems, databases, or…
- Creating Columns in Word: Layout, Breaks, and FixesTo create columns in Microsoft Word for Microsoft 365 on Windows, select the text you want to format,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.