Input Streams

Handling Multiple Words with std::cin

How do I handle multiple words input with std::cin?

Abstract art representing computer programming

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.

This Question is from the Lesson:

Input Streams

A detailed introduction to C++ Input Streams using std::cin and istringstream. Starting from the basics and progressing up to advanced use cases including creating collections of custom objects from our streams.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Input Streams

A detailed introduction to C++ Input Streams using std::cin and istringstream. Starting from the basics and progressing up to advanced use cases including creating collections of custom objects from our streams.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved