DEV Community

Cover image for String Stream in C++
Anush
Anush

Posted on

String Stream in C++

What is Stringstream Class in C++?

stringstream is a part of the C++ Standard Library, included in the sstream header, and is used for performing input and output operations on strings. It allows you to treat a string like a stream (such as cin or cout), enabling formatted input and output operations.

Commonly Used Methods of Stringstream Class in C++

  1. clear() :- To clear the stream.
  2. str() :- To get and set string object whose content is present in the stream.
  3. operator << :- Add a string to the stringstream object.
  4. operator >> :- Read something from the stringstream object.


#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main() {
    // Create a stringstream object
    stringstream ss;

    // Using operator<< to add data to the stringstream
    ss << "123 456 789";

    // Output the current content of the stringstream using str()
    cout << "Initial stringstream content: " << ss.str() << endl;

    // Variables to hold extracted values
    int a, b, c;

    // Using operator>> to extract data from the stringstream
    ss >> a >> b >> c;

    // Display the extracted values
    cout << "Extracted values: " << a << " " << b << " " << c << endl;

    // Clear the stringstream using clear()
    ss.clear();

    // Check the content after clearing (should be empty)
    cout << "After clear() - current stringstream content: " << ss.str() << endl;

    // Set a new string to the stringstream using str()
    ss.str("987 654 321");

    // Output the new content of the stringstream
    cout << "After str() set new content: " << ss.str() << endl;

    // Extract data from the stringstream again
    ss >> a >> b >> c;

    // Display the newly extracted values
    cout << "Newly extracted values: " << a << " " << b << " " << c << endl;

    // Clear the stringstream and reset the stringstream content
    ss.clear();
    ss.str("");

    // Verify that the stringstream is cleared
    cout << "Final stringstream content after clear and str reset: '" << ss.str() << "'" << endl;

    return 0;
}



Enter fullscreen mode Exit fullscreen mode

Image description

n represents the size of the string content in the stream, and m represents the size of the data being inserted or extracted.



// C++ program to demonstrate use of stringstream to count frequencies of words.
#include <bits/stdc++.h>

using namespace std;

void printFrequency(string st)
{
    // Each word it mapped to it's frequency
    map<string, int> FW;

    // Used for breaking words
    stringstream ss(st);

    // To store individual words
    string Word;

    while (ss >> Word)
        FW[Word]++;

    for (auto m : FW)
        cout << m.first << "-> " << m.second << "\n";
}


int main()
{
    string s = "May the force be with you";
    printFrequency(s);
    return 0;
}



Enter fullscreen mode Exit fullscreen mode

Top comments (0)