C++ sstream standard library details

  • 2020-04-02 01:32:31
  • OfStack

C++ sstream standard library
Let's move on to C++ style stream control. C++ introduces ostringstream, istringstream, and stringstream, and to use them to create an object you must include an sstream.h header file.

The istringstream class is used to perform input operations for C++ style streaming.
The ostringstream class is used to perform output operations for c-style streams.
The strstream class also supports input/output operations for c-style streaming.

The istringstream class is derived from istream (input stream class) and stringstreambase (c++ stringstreambase class), ostringstream is derived from ostream(output stream class) and stringstreambase (c++ stringstreambase class), and stringstream is derived from iostream(input/output stream class) and stringstreambase (c++ stringstreambase class).

Their inheritance relationship is shown in the following figure:

< img Alt = "" border = 0 border = 0 SRC =" / / files.jb51.net/file_images/article/201309/201309100900402.gif ">

Istringstream is constructed from a string object, and the istringstream class reads characters from a string object.

The constructor of istringstream is as follows:
Istringstream: : istringstream (string STR);


#include <iostream >  
#include <sstream >  
using  namespace  std;  
int  main ()   
{  
istringstream istr;  
istr.str("1 56.7",);  
//The above two processes can be simply written as istringstream istr("1 56.7"); & have spent
cout  << istr.str()<<endl;  
int  a;  
float  b;  
istr>>a;  
cout <<a<<endl;  
istr>>b;  
cout <<b<<endl;  
system("pause");  
} 

On case, construct the string flow, space will become a string argument the inner boundary of the case of a, b object input "assignment" proved that operation, a string of Spaces become the decomposition point of integer and floating point data, by using the method of boundary for we actually finished a string to integer and floating point object resolution conversion process.

The use of the STR () member function causes the istringstream object to return a string string (for example, the output operation in this example (cout) < < Istr. STR ()) .

Ostringstream is also constructed from a string object, and the ostringstream class inserts characters into a string.

The constructor of ostringstream is as follows:
Ostringstream: : ostringstream (string STR);

The sample code is as follows:


#include <iostream >  
#include <sstream >  
#include <string >  
using  namespace  std;  
int  main ()   
{  
ostringstream ostr;  
//ostr.str("abc");// If a string parameter is set during construction , So the growth operation doesn't start at the end , I'm going to change the data , The excess increases   
ostr.put('d');  
ostr.put('e');  
ostr<<"fg";  

string  gstr =  ostr.str();  
cout <<gstr;  
system("pause");  
}

In the example code, we use the put () or left shift operator can continue to insert a single character or string, ostr by STR () function returns the complete string data after the growth, but it is worth noting that when constructing object already exists within the string data, then growth will begin from the end no increase operation, but change the original data, beyond the part of the growth.

For stringstream, you don't have to tell me that it's for input and output of C++ style strings.

The constructor of stringstream looks like this:
Stringstream: : stringstream (string STR);

The sample code is as follows:


#include <iostream >  
#include <sstream >  
#include <string >  
using  namespace  std;  

int  main ()   
{  
    stringstream ostr("ccc");  
    ostr.put('d');  
    ostr.put('e');  
    ostr<<"fg";  
    string  gstr =  ostr.str();  
    cout <<gstr<<endl;  

    char  a;  
    ostr>>a;  
    cout <<a  

    system("pause");  
}

In addition, the object of the stringstream class is often used to convert string to data of various built-in types.

The sample code is as follows:


#include <iostream >  
#include <sstream >  
#include <string >  
using  namespace  std;  

int  main ()   
{  
    stringstream sstr;  
//-- -- -- -- -- -- -- -- turn int string -- -- -- -- -- -- -- -- -- -- -- & have spent
    int  a=100;  
    string  str;  
    sstr<<a;  
    sstr>>str;  
    cout <<str<<endl;  
//-- -- -- -- -- -- -- -- string transfer char [] -- -- -- -- -- -- -- -- & have spent
    sstr.clear();//If you want to perform multiple conversions using the same stringstream object, note that the clear() member function must be called after each conversion. & have spent
    string  name =  "colinguan";  
    char  cname[200];  
    sstr<<name;  
    sstr>>cname;  
    cout <<cname;  
    system("pause");  
}

The input/output system in C++ includes a record of the results of each input/output operation. This current state information is contained in an object of type io_state. Io_state is an enumerated type (like open_mode), and here are the values it contains.

Goodbit error-free
Eofbit has reached the end of the file
Failbit non-fatal input/output error, recoverable
Badbit fatal input/output error, irreversible

There are two ways to get input/output status information. One way is by calling the rdstate() function, which returns an error flag for the current state. For example, if there are no errors, rdstate() returns goodbit.

The following example shows the usage of rdstate() :


#include <iostream >  
using  namespace  std;  

int  main ()   
{  
    int  a;  
    cin >>a;  
    cout <<cin .rdstate()<<endl;  
    if (cin .rdstate() == ios ::goodbit)  
    {  
        cout <<" Input data of correct type, no errors! "<<endl;  
    }  
    if (cin .rdstate() == ios_base::failbit)  
    {  
        cout <<" Input data type error, non-fatal error, clear input buffer recovery! "<<endl;  
    }  
    system("pause");  
}

The alternative is to use any of the following functions to detect the corresponding input/output state:

Bool bad ();
Bool eof ();
Bool fail ();
Bool good ();

The following example shows the usage of the above member functions:


#include <iostream >  
using  namespace  std;  

int  main ()   
{  
    int  a;  
    cin >>a;  
    cout <<cin .rdstate()<<endl;  
    if (cin .good())  
    {  
        cout <<" Input data of correct type, no errors! "<<endl;  
    }  
    if (cin .fail())  
    {  
        cout <<" Input data type error, non-fatal error, clear input buffer recovery! "<<endl;  
    }  
    system("pause");  
}

If an error occurs, the flow state is marked as an error and you must clear the error state so that your program can continue properly. To clear the error state, use the clear() function. This function takes an argument, which is the flag value that you will set to the current state. , just take ios::goodbit as an argument.

The sample code is as follows:


#include <iostream >  
using  namespace  std;  

int  main ()   
{  
    int  a;  
    cin >>a;  
    cout <<cin .rdstate()<<endl;  
    cin .clear(ios ::goodbit);  
    cout <<cin .rdstate()<<endl;  
    system("pause");  
}

Usually, when we find that the input is wrong and needs to be corrected, we use clear() to change the mark to be correct, and we also need to clear the input buffer using the get() member function to achieve the purpose of repeating the input.

The sample code is as follows:


#include <iostream >  
using  namespace  std;  

int  main ()   
{  
    int  a;  
    while (1)  
    {  
        cin >>a;  
        if (!cin )//The condition can be rewritten as cin. Fail ()& NBSP;
        {  
            cout <<" Input is wrong ! Please re-enter "<<endl;  
            cin .clear();  
            cin .get();  
        }  
        else   
        {  
            cout <<a;  
            break ;  
        }  
    }  
    system("pause");  
}

Finally, I give an example of handling error mark of file stream. The code is as follows:

#include <iostream >  
#include <fstream >  
using  namespace  std;  

int  main ()   
{  
    ifstream myfile("c://1.txt",ios_base::in,0);  
    if (myfile.fail())  
    {  
        cout <<" File read failed or the specified file does not exist !"<<endl;  
    }  
    else   
    {  
        char  ch;  
        while (myfile.get(ch))  
        {  
            cout <<ch;  
        }  
        if (myfile.eof())  
        {  
            cout <<" The document has been read in its entirety "<<endl;  
        }  
        while (myfile.get(ch))  
        {  
            cout <<ch;  
        }  
    }  
    system("pause");  
}


Related articles: