Handling Multiple Words with std::cin
How do I handle multiple words input with std::cin?
Handling multiple words with std::cin can be tricky because the >> operator reads input until it encounters a space.
If you need to handle an input string containing multiple words, you should use std::getline() instead. Here's an example to illustrate this:
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "Please provide input: ";
std::getline(std::cin, input);
std::cout << "Input extracted: " << input;
}Please provide input: Hello World
Input extracted: Hello WorldIn this code, std::getline() reads the entire line of input, including spaces, and stores it in the input string.
Using Delimiters
If you want to split the input into multiple words and process them separately, you can use std::istringstream. This allows you to read the input line by line and then split it into words:
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string input;
std::cout << "Please provide input: ";
std::getline(std::cin, input);
std::istringstream stream(input);
std::string word;
while (stream >> word) {
std::cout << "Word extracted: "
<< word << '\n';
}
}Please provide input: Hello World from C++
Word extracted: Hello
Word extracted: World
Word extracted: from
Word extracted: C++Here, std::istringstream creates a stream from the input string. The >> operator is then used to extract each word individually.
Using std::getline() and std::istringstream provides flexibility in handling multiple words from user input, making your program more robust and versatile.
Input Streams
A detailed introduction to C++ Input Streams using std::cin and std::istringstream. Starting from the basics and progressing up to advanced use cases including creating collections of custom objects from our streams.