How to use StringStream in C++
Introduction:
The most popular streams we work with when programming in C++ are the cin as well as cout streams, that are utilized to receive input from the user and then output the result. In this case, the stream is simply the data flowing into, out of, or into a certain buffer memory where read, write, as well as clear operations can be performed.
A stream called a string stream enables the user to deal with strings and carry out different operations on them.
What is StringStream:
The classes feature in the object-oriented programming language C++ makes it simple for reuse of code scripts and organize data in a structured manner. The input and output stream is represented by the iostream class, that is used for input and output operations on objects such as user-defined data types along with primitive data types.
Let's look at an illustration of how classes in the C++ programming language are derived from one another. This indicates which class will be the parent class and which one is derived from it.
![How to use StringStream in C++/>
<!-- /wp:html -->
<!-- wp:paragraph -->
<p>As we can see, that stringstream class is a component of the ios_base class, which is the basic class from which other classes are derived. The class derived from the iostream class, that was mostly interacts with string objects, is the stringstream class. The C++ Stringstream class enables users to handle strings as a sequence of characters. It facilitates input parsing, which enables the easy conversion of any input variable into a string & vice versa. Since the stringstream class has been defined in the library, we must include it in our code in order to utilize it.</p>
<!-- /wp:paragraph -->
<!-- wp:heading -->
<h2 class=](https://static.tutorialandexample.com/cpp/how-to-use-string-stream-in-cpp1.png)
The primary purpose of any stream is to enable user actions such as uploading data to the stream, retrieving data from the stream, or carrying out additional tasks like data manipulation, etc. Let's look at a few of the often utilized C++ functions for the string stream class:
clear(): The C++ String stream's clear() method, as its name implies, erases data inside the stream.
str(): The C++ stringstream function str() is capable of both writing and reading operations. This means that we can write to the stringstream object while utilizing it to retrieve data that has been written there.
operator <<: The insertion operator (<<) is frequently encountered in C++ programming, mostly when supplying user output data. For writing data to the output stream, we utilize it in conjunction with "cout." In the same manner, we will use the insertion operator for adding data to the stringstream class object.
operator >>: The programming language C++ uses its extraction operator (>>) frequently, most notably when obtaining user input data. For extracting data from the input stream, we combine it with "cin." Likewise, we will retrieve data through the stringstream objects of classes by use of the extraction operation.
How Can I Make a C++ Stringstream Object?
Creating stringstream object using C++:
We are going to create a string stream within a C++ object now. The name of the object, along with the keyword "stringstream" construct a stringstream object. Let's look at the syntax for creating a stringstream object:
stringstream object_name;
The syntax above demonstrates, for creating a stringstream object. It's comparable for creating an object regarding the standard class. In order to incorporate the stringstream library into our code, we also require the header file.
Here is an example of how you can define a String stream using the C++ object with the code:
#include <iostream>
#include <sstream>
using namespace std;
int main () {
stringstream object_name;
cout << " String stream object is created " << endl;
return 0;
}
Output:
![How to use StringStream in C++/>
<!-- /wp:html -->
<!-- wp:paragraph -->
<p><strong>Explanation: </strong>The header file has been incorporated in the code above, then the syntax that was mentioned above is then applied in code format.</p>
<!-- /wp:paragraph -->
<!-- wp:heading -->
<h2 class=](https://static.tutorialandexample.com/cpp/how-to-use-string-stream-in-cpp2.png)
To execute the writing operation within the stringstream object, we have three options. Writing in stringstream involves adding information to the stringstream class object, which we can perform by:
Utilizing Constructor: The value of a string or any other type of data variable can be passed to the stringstream constructor when defining the stringstream object.
Using the operator insertion (<<): The insertion operation can be used in the same manner that it can be used with cout for writing data to a stringstream object.
Utilizing the str() function: As we've seen, the stringstream class object allows us to include any string value through the str() function.
The techniques for writing to the stringstream object have been demonstrated. To have a better understanding, let's now go on to the code implementing of these methods:
Code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string
var = " First Method ";
stringstream object_1(var);
cout << object_1.str() << endl;
stringstream object_2;
object_2 << " Second Method ";
cout << object_2.str() << endl;
stringstream object_3;
object_3.str(" Third Method ");
cout << object_3.str() << endl;
return 0;
}
Output:
![How to use StringStream in C++/>
<!-- /wp:html -->
<!-- wp:paragraph -->
<p><strong>Explanation: </strong>The write function within the String stream of a C++ object is performed by using the three methods that were previously described in the code above. We added data to object 3 by using the string stream class's str() function after first using the constructor technique for object 1 and then performing the insertion operation for object 2. Additionally, we have used the str() method for printing the value for every string stream object in C++.</p>
<!-- /wp:paragraph -->
<!-- wp:heading -->
<h2 class=](https://static.tutorialandexample.com/cpp/how-to-use-string-stream-in-cpp3.png)
To execute the reading operation using the stringstream object, we have two options. Accessing the data stored in the stringstream class object through reading through the stringstream allows us to:
Utilizing the extraction (>>) operator: For reading data using the stringstream object and obtaining data through the input stream, we may apply the extraction function in the same manner that we do with cin.
Utilizing the str() function: As we've seen in the tutorial above, we can retrieve data stored in the stringstream class object by using the str() method of the stringstream class.
The techniques for reading data from the stringstream object have been demonstrated. To help you understand how to use these methods better, let's now continue on to their code implementation:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
stringstream object_1;
object_1 << " First Method1 for reading the data stored in the stringstream object ";
string string_name;
while (object_1 >> string_name) {
cout << string_name << " ";
}
cout << endl;
stringstream object_2;
object_2.str(" Second Method for reading the data stored in the stringstream object ");
cout << object_2.str() << endl;
return 0;
}
Output:
![How to use StringStream in C++/>
<!-- /wp:html -->
<!-- wp:paragraph -->
<p><strong>Explanation: </strong>The stringstream object of class object_1 has been declared inside the code above, and the data has been added to it utilizing the extraction operator (>>). In the same manner, we inserted the data into the object_2 object by utilizing the stringstream within the C++ class's str() method. Additionally, we are printing the data displayed in the objects by utilizing the stringstream within the C++ class method str().</p>
<!-- /wp:paragraph -->
<!-- wp:heading -->
<h2 class=](https://static.tutorialandexample.com/cpp/how-to-use-string-stream-in-cpp4.png)
Data in the string stream within the C++ object must be deleted in order to erase the data inside the string stream object. As we've already seen in the above, we can remove the string stream data by utilizing the clear() function.
Let's look at the code implementing for clearing the data from the String stream within the C++ object using the clear() function:
Code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main () {
stringstream object_1(" The content present in the object 1 ");
string str_name;
while (object_1 >> str_name) {
cout << str_name << " ";
}
cout << endl;
object_1.clear ();
if (object_1 >> str_name) {
cout << "object 1 is not empty " << endl;
} else {
cout << "object 1 is empty" << endl;
}
return 0;
}
Output:
![How to use StringStream in C++/>
<!-- /wp:html -->
<!-- wp:paragraph -->
<p><strong>Explanation: </strong>Utilizing the constructor method, we inserted the data to the existing string stream object in the code above. Then, in order to verify that the data is actually present inside the object, we read the data utilizing the extraction operator. Subsequently, we deleted the data using the clear() function. To confirm this, we attempted to accessing the data from the string stream object once more, but we are unsuccessful because it had been erased.</p>
<!-- /wp:paragraph -->
<!-- wp:heading -->
<h2 class=](https://static.tutorialandexample.com/cpp/how-to-use-string-stream-in-cpp5.png)
The C++ string stream class has a wide range of uses. Here are a few of them:
- By introducing the string stream class inside a C++ program, a string object can be considered as a stream, allowing the user for writing data to, reading data from, along with subsequently clear data from it.
- Similarly, to cout as well as cin streams, string stream in C++ enables insertion as well as extraction from and into the string.
- With C++'s Stringstream, users may quickly transform any a primitive kind of data into a string and read input more efficiently.
Applications of string stream in C++:
Playing and working with strings is made simple in C++ by String stream. Many functions are available, including counting the words within the string, determining the frequency of a certain word in a given string, transforming any kind of primitive data into an object as well as string variable, and converting strings to integers. Now let's look at some string stream usage in C++ programs:
Calculating the Total Word Count within a String:
We may include a string in C++ that has a few words separated by spaces in it. In case we need to determine the word count in a particular string, we can physically go through the string and increment the count of words at each whitespace or towards the end. A quick and simple way to determine how many words are in a string in C++ is to use the string stream function. Let's examine and talk about its code:
Code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string input_string = "Input string";
stringstream obj(input_string);
int total_count = 0;
string buffer;
while (obj >> buffer) {
total_count++;
}
cout << " The input string has the following word count : " << total_count << endl;
return 0;
}
Output:
![How to use StringStream in C++/>
<!-- /wp:html -->
<!-- wp:paragraph -->
<p><strong>Explanation: </strong>By applying the constructor method, we are adding the data to our stringstream object in the code above. Next, we generated an integer to determine the total word count in the input string along with a string for obtaining words within the stringstream object. We incremented the count after each loop of the while loop, which worked until every word was retrieved from the provided object. Finally, we displayed the result.</p>
<!-- /wp:paragraph -->
<!-- wp:heading -->
<h2 class=](https://static.tutorialandexample.com/cpp/how-to-use-string-stream-in-cpp6.png)
The technique for determining the word count in a string was demonstrated in the preceding section, and it involved obtaining words through an extraction process. We are now able to determine the frequency of each word by storing it on a map. Let's examine its code to gain a better understanding of it:
Code:
#include <bits/stdc++.h>
using namespace std;
void printing_freq(string st)
{
map < string, int > Freq_word;
stringstream ss(st);
string input_word;
while (ss >> input_word)
Freq_word[input_word]++;
for (auto m : Freq_word)
cout << m.first << " : " << m.second << "\n";
}
int main()
{
string s = " C Python Java C C++ Node.js Python";
printing_freq(s);
return 0;
}
Output:
![How to use StringStream in C++/>
<!-- /wp:html -->
<!-- wp:paragraph -->
<p><strong>Explanation: </strong>By applying the constructor technique, we inserted the data to our stringstream object in the above program. Next, we constructed a map to record the occurrence of the specific word along with a string for obtaining words within the stringstream object. After each word has been retrieved from the provided object, we repeat the while loop, increasing the total count of each word along the way. Finally, we displayed each word along with its frequency by iterating over the map.</p>
<!-- /wp:paragraph -->
<!-- wp:heading -->
<h2 class=](https://static.tutorialandexample.com/cpp/how-to-use-string-stream-in-cpp7.png)
A stringstream describes a kind of stream which lets the user interact with strings and do different kinds of operations on them. The iostream class drives the Stringstream class, which specializes in working with string objects and then enables users to handle strings like a stream of characters. The C++ programming language's header file contains the definition of Stringstream. The stringstream class uses the following four standard methods:
The stringstream object's data can be cleared using the clear() function. For adding or reading the data within the stringstream object, utilize the str() function. The extraction operator (>>) retrieves data within the object, as its name implies. Data is added to an existing stringstream object with the insertion operator (\\). The str() function, constructor, as well as insertion operator, are the three methods available for inserting data to a stringstream object.
There are two methods for reading data within the stringstream object: using the extraction operator or the built-in str() function. In C++, Stringstream facilitates easy input processing and allows users to quickly transform any basic data type to a string.