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 World

In 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.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Reading a Full Line with std::getline()
How can I read a full line of input including spaces?
Use of peek() Method
What are the use cases of peek() in input streams?
Reading Multiple Objects from Stream
What is the best way to read multiple objects from a stream?
Using Custom Delimiters with std::getline()
How can I use std::getline() with a custom delimiter?
std::getline() vs get()
What is the difference between std::getline() and the get() method?
Creating Objects from Stream
How do I create a dynamic array of objects from stream data?
Third-Party Libraries for Input Streams
What third-party libraries simplify working with input streams?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant