×

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

C++ Encapsulation

The following two essential components are present in all C++ programmes: Functions are the parts of a programme that perform actions, and they are termed programme statements (code).Program data is the...

4 minutes read.

C++ Iterators

What are iterators ? Iterators are among the four foundations of the C++ Standard Template Library, also known as the STL. The memory address of the STL container classes is pointed...

15 minutes read.

Hospital Management Project in C++

The following capabilities are required to build a hospital management project: These are as follows: hospitals' names, contact information, and lists of doctors and patients. Activities Supported Hospital Data Print Patients' data to...

4 minutes read.

Malloc() and new in C++

In C ++, malloc () and new are used for the same thing. During runtime, they are used to allocate memory. Malloc () and the new, on the other hand,...

4 minutes read.

System() function in C++

As a part of the c/c+ standard library, the system() function passes commands to be executed by the operating system’s command processor or terminal and returns the completed command. We...

2 minutes read.

Type conversion in C++

Type conversion is the process of changing the type of variables in a program. The ultimate goal of type conversions is to allow variables of a single data type operate with...

7 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

C++ Global Variable

In C++, a global variable is a variable that is defined outside of any function or class and can be accessed by any function or class in the program. Global...

4 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.

Use of Inheritance in C++

What is inheritance in c++? Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the...

4 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

Multiset in C++

Introduction Multisets are part of the C++ STL, or Standard Template Library. In C++, a multiset is a set of associative containers that hold ordered items. Items in a multiset can...

10 minutes read.

Boost split in C++ library

Boost::split in C++ library Boost offers strong tools for adding mature, well-tested libraries to the C++ standard library. The boost: split function, which is a component of the Boost string algorithm...

2 minutes read.

Smart pointers in C++

What are Pointers ? Pointers are often used to keep track of a variable's address. A null value can be assigned to a pointer. Pass by reference can be used to...

6 minutes read.

How to create a stack in C++

A stack is a data structure, which is of linear type. A specific order has to be followed while inserting and deleting the elements from the stack. Generally, stack follows...

5 minutes read.

C++ Forward Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.

Queue in C++

What is Queue? As the name suggests, the queue is the type of data structure that follows the FIFO (First In - First Out) mechanism. In simple words, it is...

4 minutes read.

C++ String

A string is a collection of characters. C++ programming language supports both C string as well as standard C++ library string. In C++, string is an object of std::string class. C Style String The C style...

5 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.