StringStream in C++ is similar to cin and cout streams and allows us to work with strings. Like other streams, we can perform read, write, and clear operations on a StringStream object. The standard methods used to perform these operations are defined in the StringStream class.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What Is the StringStream Class?

The StringStream class in C++ is derived from the iostream class. Similar to other stream-based classes, StringStream in C++ allows performing insertion, extraction, and other operations. It is commonly used in parsing inputs and converting strings to numbers, and vice-versa. The most commonly used methods and operators from this class are:

  • str(): Gets and sets the string object’s content in the stream
  • clear(): Clears the stream
  • <<: Adds a new string to the StringStream object
  • >>: Reads the content from the StringStream object

StringStream class’s objects use a buffer of a sequence character that can be directly accessed and worked with as a string object.

How to Create a StringStream in C++?

Using the <sstream> header file, you can convert a string to create a StringStream object. All you need to do is use the type stringstream to create a constructor and pass the string as an input to it. The below example shows how to convert a string to a StringStream object easily.

#include <iostream>

#include <string>

#include <sstream>

using namespace std;

int main(){

    // Declaring string

    string init_string = "Welcome to Simplilearn";  

    // Converting to stringstream object

    stringstream ss(init_string); 

    cout << "This is a stringstream object\n"; 

    return 0;

}

Output

StringStream_in_Cpp_1

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

How to Perform Insertion or Write Operation in StringStream in C++?

We can write into a StringStream in C++ just like the cout << operator. In the below example, we will create a StringStream object as we have created in the previous section. We will then use a buffer, a while loop, and a for loop to print the content of the StringStream object in the form of arrays of string. The code will check if the stream is empty and proceed based on the outcome. If the buffer is empty, the program will simply exit the code. On the other hand, if the buffer is not empty, it will write the content of the stream into the buffer and enter the loops.

#include <iostream>

#include <string>

#include <sstream>

using namespace std;

int main() {

    string init_string = "Welcome to Simplilearn";  

    // Creating stringstream object

    stringstream ss(init_string); 

    cout << "This is a StringStream object\n";     

    // Array to store returned words

    string ret_words[5];

    string buf;

        int x = 0; 

    while (ss >> buf) {

        ret_words[x] = buf;

        cout << "The Buffer: " << buf << endl;

        x++;

    } 

    // Printing the string

    cout << "Printing the array of strings\n";

    for (int y = 0; y < x; y++) {

        cout << ret_words[y] << endl;

    } 

    return 0;

}

Output

StringStream_in_Cpp_2

At the base level, this is as simple as directly assigning the string data to the buffer. This can easily be done with the below code.

#include <iostream>

#include <string>

#include <sstream>

using namespace std;

int main() {

  // Using << operator

  stringstream s;

  s<< “hello,world!!”;

  // Using the str() function

  stringstream ss;

  ss.str(“Welcome to Simplelearn!!”);

}

This will show no output as it will just write the content in the StringStream object.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

How to Perform Extraction or Read Operation in StringStream in C++

Like the insertion, we can also perform extraction on StringStream in C++, like the cin >> operator. We can again do this by using the >> operator or the str() function. In the below example, we will use the above code to first write into StringStream and then use both the str() function to read the content.

#include <iostream>

#include <string>

#include <sstream>

using namespace std;

int main() {

  // Using str() function to read

  stringstream s;

  s<< “hello world!!”;

  cout<<s.str();

}

Output

StringStream_in_Cpp_3

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

How to Clear StringStream in C++

You can easily clear the content of a StringStream object by using the predefined ss.clear() function. The function will erase the data in the buffer and make the object empty. The below code demonstrates how to clear StringStream in C++.

#include <iostream>

#include <string>

#include <sstream>

using namespace std; 

int main() {

    string init_string = "Welcome to Simplilearn";  

    // Creating stringstream object

    stringstream ss(init_string);

    cout << "This is a StringStream object\n";

    // Array to store returned words

    string ret_words[5];

     string buf;

        int x = 0;

 while (ss >> buf) {

        ret_words[x] = buf;

        cout << "The Buffer: " << buf << endl;

        x++;

    }

    // Printing the string

    cout << "Printing the array of strings\n";

    for (int y = 0; y < x; y++) {

        cout << ret_words[y] << endl;

    }

    ss.clear();

    if (ss >> buf) {

        cout << "StringStream Object Still Contains " << buf << endl;

    }

    else {

        cout << "StringStream is empty!\n";

    }

    return 0;

}

Output

StringStream_in_Cpp_4.

In the above code, we use the ss.clear() function to empty the string and then confirm the same by checking the content with the if ss>>buf statement. Since, the if statement fails, the result from the else statement is shown in the output at the end to confirm that the object is now empty.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What Are the Applications of StringStream in C++

StringStream in C++ has several applications that you can use in your programming to achieve different results. Some of the key applications of StringStream are:

Application 1: Counting the Number of Words Present in a String

With StringStream in C++, you can count individual words from a StringStream object. Here’s the program to do that.

#include <iostream>

#include <sstream>

#include <string>

using namespace std;

int totalWords(string s)

{

// breaking input to individual words in string stream

stringstream str(s); // breaks words

string ind_Word; // stores individual words

int count = 0;

while (str >> ind_Word)

count++;

return count;

}

// Driver code

int main(){

string str = "Hello, Welcome to Simplilearn! "

"Here you'll learn C++ Programming.";

cout << "Total words are: " << totalWords(str);

return 0;

}

Output

StringStream_in_Cpp_5

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Application 2: Converting Numbers to Strings and Vice-Versa

With the insertion and extraction operations of StringStream in C++, you can convert the numbers to strings and vice-versa. Here’s the complete code to do that.

#include <iostream>

#include <sstream>

#include <string>

using namespace std;

int main(){

    //Converting numbers to string   

    stringstream s;  

    int num1 = 2019;

    double num2 = 3.142;

    s << num1 << " " << num2;  

    string Str1, Str2;

    s >> Str1 >> Str2;      

    cout<<"Converting numbers to string:"<<endl;

    cout << "Str1 = "<<Str1 << " " << "Str2 = "<<Str2 << endl;    

    //Converting string to numbers

    stringstream n;

    n << "2019 3.142"; // inserting a string into the stream

    int Int1;

    double Doub1;    

    n >> Int1 >> Doub1;

    cout<<"Converting string to numbers:"<<endl;

    cout << "Int1 = "<<Int1 << " " <<"Doub1 = "<< Doub1 << endl;

}

Output

StringStream_in_Cpp_6.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Application 3: Printing Frequencies of Individual Words of a String

With StringStream in C++, you can count and print the frequencies of individual words. This means that you can print how many times a word is repeated in a string. The code for doing this is as below.

#include <iostream>

#include <sstream>

#include <string>

#include <map>

using namespace std;

void countFreq(string s)

{

// We use map to map each word with its frequency

map<string, int> WF;

stringstream ss(s); // breaks words

string ind_Word; // stores individual words

while (ss >> ind_Word)

WF[ind_Word]++;

map<string, int>::iterator m;

for (m = WF.begin(); m != WF.end(); m++)

cout << m->first << " -> "

<< m->second << "\n";

}

// Main code

int main()

{

string s = "Practice Quiz. You can Practice here with this quiz.";

countFreq(s);

return 0;

}

Output

StringStream_in_Cpp_7.

As you can see in the output, the code counts and prints the frequency of each word. You can also see that the words are counted as case-sensitive. Hence, the words Quiz and quiz are considered different.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Conclusion

In this article, you have learned everything about StringStream in C++, right from what it is to different operations that can be performed on it, along with examples. You can now use the StringStream class in your code and read, write, or clear the string objects through it. If you want to learn about more such fundamental concepts of C++ and use them, you can refer to Simplilearn's C++ Tutorial for Beginners. The tutorials are specifically designed to help beginners scoop into C++ Programming. If you have the basic knowledge, you can go for our UpSkill programs, dedicated to assisting programmers in sharpening their skills and upscaling their understanding. However, if you are looking for a more advanced course, opt for our Full Stack Web Development Program. The program will help you get acquainted with the concepts of multiple programming languages used in Web Development. It is also loaded with numerous hours of applied learning and self-paced tutorials to help you excel in the field of Web Development.

What Is the StringStream Class?

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 15 Apr, 2024

6 Months$ 8,000
Full Stack Java Developer

Cohort Starts: 2 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 3 Apr, 2024

11 Months$ 1,499
Full Stack Developer - MERN Stack

Cohort Starts: 3 Apr, 2024

6 Months$ 1,449