The Wayback Machine - https://web.archive.org/web/20241119211106/https://www.geeksforgeeks.org/stringstream-c-applications/
Open In App

stringstream in C++ and its Applications

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input. 

Basic methods are:

  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.

stringstream is a versatile class for manipulating strings in memory. The C++ Course explains how to use stringstream for input and output operations, enhancing your string handling skills.

Examples:

1. Count the number of words in a string

Examples:

Input: Asipu Pawan Kumar
Output: 3

Input: Geeks For Geeks Ide
Output: 4

Below is the C++ program to implement the above approach-

C++
// C++ program to count words in  
// a string using stringstream.
#include <iostream>
#include <sstream>
#include<string>
using namespace std;

int countWords(string str)
{
    // Breaking input into word 
    // using string stream
  
    // Used for breaking words
    stringstream s(str); 
  
    // To store individual words
    string word; 

    int count = 0;
    while (s >> word)
        count++;
    return count;
}

// Driver code
int main()
{
    string s = "geeks for geeks geeks "
               "contribution placements";
    cout << " Number of words are: " << countWords(s);
    return 0;
}

Output
 Number of words are: 6

Time complexity: O(n), Where n is the length of the string.
Auxiliary space: O(m), Where m is the number of words in the string.

2. Print frequencies of individual words in a string

Examples:

Input: Geeks For Geeks Quiz Geeks Quiz Practice Practice
Output: For -> 1
             Geeks -> 3
             Practice -> 2
             Quiz -> 2

Input: Word String Frequency String
Output: Frequency -> 1
              String -> 2
              Word -> 1     

Below is the C++ program to implement the above approach-

C++
// 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";
}

// Driver code
int main()
{
    string s = "Geeks For Geeks Ide";
    printFrequency(s);
    return 0;
}

Output
For-> 1
Geeks-> 2
Ide-> 1

Time complexity: O(n log(k)), n is the total number of words in the input string, and k is the number of unique words.
Auxiliary space: O(n).

3. Convert Integer to string

Since, the insertion and extraction operators of string stream work with different data types. So that’s why it works well with integers.

We will insert an integer into the string stream and after extracting that into a string, that integer value will become a string.

Code-

C++
// C++ program to demonstrate the
// use of a stringstream to
// convert int to string
#include <iostream>
#include <sstream>
using namespace std;

// Driver code
int main()
{
    int val=123;

    // object from the class stringstream
    stringstream geek;

    // inserting integer val in geek stream
    geek << val;

    // The object has the value 123
    // and stream it to the string x
    string x;
    geek >> x;

    // Now the string x holds the
    // value 123
    cout<<x+"4"<<endl;
    return 0;
}

Output
1234

Time complexity: O(log(val))
Auxiliary space: O(n)

Removing spaces from a string using Stringstream
Converting Strings to Numbers in C/C++



Previous Article
Next Article

Similar Reads

C++ string class and its applications
In C++ we can store string by one of the two ways – C style stringsstring class (discussed in this post) In this post, the second method is discussed. string class is part of C++ library that supports a lot much functionality over C style strings. C++ string class internally uses char array to store character but all memory management, allocation,
6 min read
C++ String Class and its Applications
C++ string class and its applications have more functions as discussed in this article String vs Character Array In C++, in addition to a character array, there exists a similar kind of way to implement string, that is using a string class which is a part of C++ standard library.We need to add a header file to implement string using string class. T
4 min read
strchr() function in C++ and its applications
In C++, strchr() is a predefined function used for finding the occurrence of a character in a string. It is present in cstring header file. Syntax: // Returns pointer to the first occurrence// of c in str[]char *strchr(const char *str, int c) Note that c is passed as its int promotion, but it is internally treated as char.Application Given a string
4 min read
MakeFile in C++ and its applications
In C++, building a simple program is easy with the help of CLI of the compiler. But it becomes progressively difficult to maintain and build the project when its size increases. We may need to write multiple lines of commands just to simply compile it. This can be simplified by using Makefile for the project and build it using this makefile. In thi
5 min read
Node having maximum number of nodes less than its value in its subtree
Given a Binary Tree, the task is to find the node from the given tree which has the maximum number of nodes in its subtree with values less than the value of that node. In the case of multiple possible nodes with the same number of maximum nodes, then return any such node. Examples: Input: 4 / \ 6 10 / \ / \2 3 7 14 / 5 Output: 6Explanation:Node wi
10 min read
INT_MAX and INT_MIN in C/C++ and Applications
Most of the time, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold, but remembering such a large and precise number comes out to be a difficult job. Therefore, C/C++ has certain macros to represent these numbers, so that these can be directly assigned to the variable without ac
7 min read
Applications and Popularities of C++
C++ is a programming language, which has imperative and object-oriented programming(OOPs) features. It is referred to as a middle-level programming language. C++ was developed by Bjarne Stroustrup at Bell Labs in 1979. It has first appeared in the year of 1985. It supports official, object-oriented and generic programming. It is having a rich stand
5 min read
Find sum of a number and its maximum prime factor
Given an integer N, the task is to find the sum of N and it's maximum prime factor.Examples: Input: 19 Output: 38 Maximum prime factor of 19 is 19. Hence, 19 + 19 = 38Input: 8 Output: 10 8 + 2 = 10 Approach: Find the largest prime factor of the number and store it in maxPrimeFact then print the value of N + maxPrimeFact.Below is the implementation
6 min read
unordered_multimap and its application
Allows Duplicates: We have discussed unordered_map in our previous post, but there is a limitation, we can not store duplicates in unordered_map, that is if we have a key-value pair already in our unordered_multimap and another pair is inserted, then both will be there whereas in case of unordered_map the previous value corresponding to the key is
7 min read
is_permutation() in C++ and its application for anagram search
is_permutations() is used to check if two containers like string and vector are permutation of each other. It accepts three parameters, the first two parameters are begin and end positions of first object and third parameter begin position of second object. C/C++ Code // C++ program to demonstrate working of // is_permutation() #include <bits/st
2 min read
iscntrl() in C++ and its application to find control characters
In C++, iscntrl() is a predefined function used for string and character handling. cstring is the header file required for string functions and cctype is the header file required for character functions. A control character is one which is not a printable character i.e, it does not occupy a printing position on a display. This function is used to c
3 min read
C++ bitset and its application
A bitset is an array of bools but each boolean value is not stored in a separate byte instead, bitset optimizes the space such that each boolean value takes 1-bit space only, so space taken by bitset is less than that of an array of bool or vector of bool. A limitation of the bitset is that size must be known at compile time i.e. size of the bitset
6 min read
Maximum array elements that can be removed along with its adjacent values to empty given array
Given an array arr[] of size N. In each operation, pick an array element X and remove all array elements in the range [X - 1, X + 1]. The task is to find the maximum number of steps required such that no coins left in the array. Examples: Input: coins [] = {5, 1, 3, 2, 6, 7, 4} Output: 4 Explanation: Picking the coin coins[1] modifies the array arr
7 min read
Count of integers having difference with its reverse equal to D
Given an integer D, the task is to find the count of all possible positive integers N such that reverse(N) = N + D. Examples: Input: D = 63 Output: 2 Explanation: For N = 18, 18 + 63 = 81, which satisfies the condition N + D = reverse(N). For N = 29, 29 + 63 = 92, which satisfies the condition N + D = reverse(N). Therefore, the required output is 2
13 min read
Maximize groups to be formed such that product of size of group with its minimum element is at least K
Given an array, arr[] of length N, and an integer K. The value of the i-th element is arr[i]. The task is to find the maximum number of groups such that for each group the product of the number of elements in that group and the minimum element is at least K. Note: Every element should belong to exactly one group and some elements may not be part of
8 min read
Reduce Array and Maximize sum by deleting one occurrence of A[i] and all occurrences of A[i]+1 and A[i]-1
Given an array A[] having N positive integers, the task is to perform the following operations and maximize the sum obtained while reducing the array: Select an array element (say A[i]) and delete one occurrence of that element and add A[i] to the sum.Delete all the occurrences of A[i]-1 and A[i]+1.Perform these operations until the array is empty.
8 min read
Catching Base and Derived Classes as Exceptions in C++ and Java
An Exception is an unwanted error or hurdle that a program throws while compiling. There are various methods to handle an exception which is termed exceptional handling. Let's discuss what is Exception Handling and how we catch base and derived classes as an exception in C++: If both base and derived classes are caught as exceptions, then the catch
4 min read
fesetround() and fegetround() in C++ and their application
fesetround() It sets the specified floating point rounding direction or the "current rounding direction" which is expected to be one of the floating point rounding macros. It is used with rint(), nearbyint() and other rounding functions in C++. Syntax: int fesetround( int round ); where round can be FE_TONEAREST, FE_DOWNWARD, FE_UPWARD, FE_TOWARDZE
3 min read
Queries to insert, delete one occurrence of a number and print the least and most frequent element
Given Q queries of type 1, 2, 3 and 4 as described below. Type-1: Insert a number to the list.Type-2: Delete only one occurrence of a number if exists.Type-3: Print the least frequent element, if multiple elements exist then print the greatest among them.Type-4: Print the most frequent element, if multiple elements exist then print the smallest amo
14 min read
Get first and last elements from Array and Vector in CPP
Given an array, find first and last elements of it. Input: {4, 5, 7, 13, 25, 65, 98} Output: First element: 4 Last element: 98 In C++, we can use sizeof operator to find number of elements in an array. // C++ Program to print first and last element in an array #include <iostream> using namespace std; int main() { int arr[] = { 4, 5, 7, 13, 25
2 min read
Similarities and Differences between Ruby and C++
There are many similarities between C++ and Ruby, some of them are: Just like C++, in Ruby… As in C++, public, private, and protected works similarly in Ruby also .Inheritance syntax is still only one character, but it’s < instead of : in Ruby.The way ‘namespace’ is used in C++, in the similar way we may put our code into “modules” in ruby.There
3 min read
Similarities and Difference between Java and C++
Nowadays Java and C++ programming languages are vastly used in competitive coding. Due to some awesome features, these two programming languages are widely used in industries as well as comepetitive programming . C++ is a widely popular language among coders for its efficiency, high speed, and dynamic memory utilization. Java is widely used in the
6 min read
Split a Binary String such that count of 0s and 1s in left and right substrings is maximum
Given a binary string, str of length N, the task is to find the maximum sum of the count of 0s on the left substring and count of 1s on the right substring possible by splitting the binary string into two non-empty substrings. Examples: Input: str = "000111" Output: 6 Explanation: Splitting the binary string into "000" and "111". Count of 0s in the
7 min read
Sort and separate odd and even numbers in an Array using custom comparator
Given an array arr[], containing N elements, the task is to sort and separate odd and even numbers in an Array using a custom comparator. Example: Input: arr[] = { 5, 3, 2, 8, 7, 4, 6, 9, 1 }Output: 2 4 6 8 1 3 5 7 9 Input: arr[] = { 12, 15, 6, 2, 7, 13, 9, 4 }Output: 2 4 6 12 7 9 13 15 Approach: As we know std::sort() is used for sorting in increa
5 min read
Generate an array of given size with equal count and sum of odd and even numbers
Given an integer N, the task is to find an array of length N that contains same count of odd and even elements with an equal sum of even and odd elements in the array.Note: Print -1 if no such array is possible. Examples: Input: N = 4 Output: 1 2 5 4 Explanation: Even elements of the array - {2, 4}, S(even) = 6 Odd elements of the array - {1, 5}, S
8 min read
isupper() and islower() and their application in C++
In C++, isupper() and islower() are predefined functions used for string and character handling. cstring.h is the header file required for string functions and cctype.h is the headerfile required for character functions. isupper() Function: This function is used to check if the argument contains any uppercase letters such as A, B, C, D, ..., Z. Syn
2 min read
Change/add only one character and print '*' exactly 20 times
In the below code, change/add only one character and print '*' exactly 20 times. int main() { int i, n = 20; for (i = 0; i < n; i--) printf("*"); getchar(); return 0; } Solutions:1. Replace i by n in for loop's third expression C/C++ Code #include <iostream> using namespace std; int main() { int i, n = 20; for (i = 0; i < n; n--) cout
5 min read
Data type of character constants in C and C++
In C, data type of character constants is int, but in C++, data type of same is char. If we save below program as test.c then we get 4 as output (assuming size of integer is 4 bytes) and if we save the same program as test.cpp then we get 1(assuming size of char is 1 byte) C/C++ Code // C++ program demonstrating that data type of character // const
1 min read
Can We Use Function on Left Side of an Expression in C and C++?
In C, it is not possible to have function names on the left side of an expression, but it's possible in C++. How can we use the function on the left side of an expression in C++? In C++, only the functions which return some reference variables can be used on the left side of an expression. The reference works in a similar way to pointers, so whenev
1 min read
Comparison of Exception Handling in C++ and Java
Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. Following are the differences between Java and C++ exception handling: Java C++ Only throwable objects can be thrown as exceptions.All types can be thrown as exceptions.We can catch Exception objects to catch all kinds o
4 min read
Practice Tags :
three90RightbarBannerImg