×

Processing strings using std string stream in C++

A string class object called std: string stream is used to streamline into various variables, just as files can pour into strings. This class's things make use of a string buffer that holds a string of characters. A string object representing this string of characters can be retrieved.

Header Document

#include<stream>

1. Using std: string stream to stream an integer from a string

Using an input string stream object std: string stream from the header is one technique to spray a series. The extraction operator (>>) can be used to stream and store a series after an std:string stream object has been constructed. Until whitespace is encountered or the stream fails, the extraction operator will continue to read.

The std:string stream is illustrated below:

Example 1:

// C++ program to illustrate C++ program that displays std:: string stream
 std::istringstream
#include <iostream>
#include <sstream>
#include <string>
using std::istringstream;
using std::string;
using std::cout;
// Driver Number
int main()
{
    // Enter a string
    string a("1 2 3");
    // class of istringstream objects
    istringstream my_stream(a);
 
    // n-bit storage variable
    int n;
    // Count till there is a blank spot.
   //is encountered
    my_stream >> n;
    // the number on paper
    cout << n << "\n";
}

Output:

1

To ascertain whether the most recent extraction operation failed, the std::istringstream object can be utilized as a Boolean alternatively. This occurs if there are no more characters in the stream. We can stream the string once more if there are still characters in the stream.

The complete expression my stream >> n is a std::istringstream object that returns a Boolean, i.e., true if the stream is possible; otherwise, return false. The extraction operator >> writes the stream to the variable on the operator's right and returns the std::istringstream object.

The following describes how to use the std::istringstream in the manner described above:

Example 2:

// A C++ program that displays std:: istringstream
#include <iostream>
#include <sstream>
#include <string>
using std::istringstream;
using std::string;
using std::cout;
 
// Driver Number
int main()
{
    // Enter a string
    string a("1 2 3");
 
    // class of istringstream objects
    istringstream my_stream(a)
    // n-bit storage variable
    int n;
    // examining the stream to determine its condition
    // successful printing of outcomes
    while (my_stream) {
 
        // stream until space is reached
        // encountered
        my_stream >> n;
 
        // if my stream contains data
        if (my_stream) {
            cout << "That stream was  successful: "
                 << n << "\n";
        }
 
        // Failure to print without it
        else {
            cout << "That stream was  NOT successful!"
                 << "\n";
        }
    }
 
    return 0;
}

Output:

Processing strings using std: string stream in C++

2. Strings of Different Types

The string in the examples is made up entirely of whitespace and int-convertible characters. The column can be used as shown below if it has mixed types or more than one data type in the stream.

The standard is illustrated below in this way:

1st Program:

// A C++ program that displays std:: istringstream
// when an integer follows a character in a string
#include <iostream>
#include <sstream>
#include <string>
using std::istringstream;
using std::string;
using std::cout;
// Driver Number
int main()
{
    // Enter a string
    string str("1, 2, 3");
 
    // class of istringstream objects
    istringstream my_stream(str);
 
    // n-bit variable to hold the number
    // and ch, the character
    char c;
    int n;
 
    // until the input stream is legitimate, navigate
    while (my_stream >> n >> c) {
 
        cout << "That stream was successful: "
             << n << " " << c << "\n";
    }
    Cout << "The stream has failed."
         << "\n";
 
    return 0;
}

Output:

Processing strings using std: string stream in C++

2nd Program:

// C++ example program for std:: istringstream
//  tokenize the string with
#include <iostream>
#include <sstream>
#include <string>
using std::istringstream;
using std::string;
using std::cout;
 
// Driver Number
int main()
{
    // Enter a string
    string str("abc, def,   ghi");
 
    // class Object of istringstream
    istringstream my_stream(str);
 
    // To save the stream string
    string token;
 
    size_t pos = -1;
 
    // Continue until the stream is legitimate.
    while (my_stream >> token) {
 
        // If "," is discovered, tokenize.
        // the token string
        while ((pos = token.rfind(','))
               != std::string::npos) {
            token.erase(pos, 1);
        }
 
        // Tokenize the string, and print it.
        cout << token << '\n';
    }
}

Output:

Processing strings using std: string stream in C++

Related Topics

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 minutes read.

How to calculate size of string in C++

What is string in C++? In C++, a string is a sequence of characters. The string data type is part of the Standard Template Library (STL) and is defined in the...

4 minutes read.

SDL library in C++ with Examples

SDL stands for Simple DirectMedia Layer. Using OpenGL and Direct3D, it is a cross-platform development library created to give users low-level access to audio, keyboard, mouse, joystick, and graphics hardware....

3 minutes read.

C++ Writing to file

In file handling, write() function is used to write data into the file. The write() uses ofstream or fstream library to write into the file. Syntax file-stream-class   file-stream-object;   file-stream-object.write((char *)&var , sizeof (var)); The write() takes two arguments. The first argument is the address of variable var...

2 minutes read.

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

Program to arrange an array in alternate positive and negative numbers

Let’s say, there is given an array arr, arrange the array in such a way that every positive number is followed by a negative number. If there are extra positive...

4 minutes read.

Program that produces different results in C and C++

Introduction: There are many such programs that compile run both in C and C++ but give different outcomes when compiled by the C and C++ compilers. There are a variety of such...

6 minutes read.

Decltype type Specifier in C++

The primary use of C++ decltype is to inspect the declaration type of an entity in an expression. The auto keyword can declare a particular type of variable, whereas the...

4 minutes read.

C++ Dijkstra Algorithm Using the Priority Queue

In this article we will be finding the shortest routes from a source vertex in a graph to all vertices in the graph, given a graph and a source vertex...

5 minutes read.

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 minutes read.

Virtual Functions and Runtime Polymorphism in C++

In this tutorial, we will explore more on virtual functions and runtime polymorphism in the most useful language C++. A virtual function is a member function with the keyword virtual used...

6 minutes read.

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages. C++ Function A function is a set of statements that executes a task....

5 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

Random Number Generator in C++

In programming, we need to frequently create the randomly. For example, a dice game, handing out cards to players, apps for rearranging tunes, etc. T There are two tools available in...

4 minutes read.

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.

Palindrome using For loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

3 minutes read.