Open In App

How to Handle Multiple String Inputs with Spaces in C++?

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, strings are a sequence of characters that might contain spaces in many cases but we can read only the input text till whitespace using cin. In this article, we will learn how to handle multiple string inputs with spaces in C++.

Example:

Input:
Enter multiple strings:
String1
String2
Output:
You Entered: String1
You Entered: String2

Reading Multiple String Inputs with Spaces in C++

To handle multiple string inputs with spaces in C++, we can use the std::getline() method provided by the STL library that is commonly used for reading a line from the input stream. It reads a string until the newline character occurs.

C++ Program to Handle Multiple String Inputs with Spaces

The following program illustrates how we can handle multiple string inputs with spaces using the std::getline method in C++.

C++
// C++ Program to Handle Multiple String Inputs with Spaces

#include <iostream>
#include <string>
using namespace std;

int main()
{
    // Initialize a string to take input from the user
    string input;
    cout << "Enter multiple strings:" << endl;
    while (getline(cin, input)) {
        // Print multiple string inputs after each space
        cout << "You entered: " << input << endl;
    }
    return 0;
}

Output
Enter multiple strings:


Output

Enter multiple strings:
String1
You entered: String1
String2
You entered: String2


Time Complexity: O(N*K) where N is the number of strings entered and K is average length of each string.
Auxiliary Space: O(N*K)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads