How to Use stringstream for Input With Spaces in C++?
In C++, the std::stringstream
class is a stream class to operate on strings and is very useful when we want to operate on a string as if it were a stream (like cin or cout). In this article, we will learn how to use string streams for input with spaces in C++.
Example:
Input:
string = “Hello, World!”
Output:
Hello, World! //Read the string into a string stream and output each word
Taking Input with Spaces Using stringstream in C++
In C++, the stringstream is used to create a stream to a string. This stream can be used to read the data from the string using >> (extraction operator) but it will read the input till the whitespace. The rest of the input would require more use of the>> operator making it not suitable for working with input strings with spaces.
To use stringstream for strings with spaces, we can use the std::getline() function that can read from the stream till the given delimiter.
Syntax of std::getline() in C++
getline(stream, dest, delim)
Here,
- stream: stream to read data from
dest:
string variable that will hold the read data.delim:
delimiter that specifies where to stop reading.
C++ Program to Use String Streams for Input with Spaces
The below example demonstrates how to use string streams for input with spaces in C++.
C++
// C++ Program to illustrate how to use stringstream for input with spaces
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
// Initialize a string
string myString = "Hello, World!";
// Use stringstream for input with spaces
stringstream ss(myString);
string word;
while (getline(ss, word, '\0')) {
cout << word << endl;
}
return 0;
}
Output
Hello, World!
Time Complexity: O(N), here N is the length of the string
Auxiliary Space: O(N)