Monday, December 9, 2024

basic_istream

Overview
basic_istream are designed to receive inputs from various sources such as console, files and strings.

Details
The class template basic_istream provides support for high level input operations on character streams. The supported operations include formatted input (e.g. integer values or whitespace-separated characters and characters strings) and unformatted input (e.g. raw characters and character arrays).

Syntax
template<class CharT, class Traits = char_traits<CharT>> 
class basic_istream: public basic_ios<CharT,Traits> 
where CharT can be char or wchar_t. It's derived from basic_ios class.

member types
Following properties are defined.
NameDefinition
char_typechar,wchar_t
traits_typechar_traits<char_type>
int_typechar_traits<char_type>::int_type
pos_typechar_traits<char_type>::pos_type
off_typechar_traits<char_type>::off_type

sentry class
sentry is a subclass that's constructed in local scope at the beginning of each member function of basic_istream that performs input (both formatted and unformatted).

All member functions of basic_istream that perform an input operation automatically construct an object of this class and then evaluate it using the bool operator function. Only if this object evaluates to true, the function attempts the input operation.

The operator>> formatted input operations of basic_istream construct the sentry object by passing false to noskipws argument, resulting in white space skipping. All other member functions that construct a sentry object pass true as second argument, resulting in no white space skipping.

Constructor
Syntax
sentry( basic_istream& is, bool noskipws = false )

Its constructor prepares the input stream by doing the following:
  • Checks if the stream is already in a failed state. If so returns.
  • Flushes the tie()'d output streams.
  • Skips leading whitespace unless noskipws flag is set
  • Performs other implementation-defined tasks if necessary.
All cleanup, if necessary, is performed in the destructor, so that it is guaranteed to happen if exceptions are thrown during input.

Method
Syntax
operator bool()
Checks if the preparation was successful or not. Returns true or false.

Example
struct rect
{
    int  h,w;
};

istream& operator>>(istream& is,  rect& r)
{
    istream::sentry s(is);
    if (s) 
        is >> r.h >> r.w;

    return is;
}

    istringstream ss{"   10 20"};
    rect r;
    //creates rect{10,20}
    ss >> r;

Constructor
NameDescription
basic_istream
(basic_streambuf* sb)
Constructs an object of class basic_istream, assigning initial values to its member objects by calling init(sb). If sb is a null pointer, the stream is placed in error state by setting its badbit.

Example
    istream os(cin.rdbuf());

Formatted Input
operator >>
The overloaded operator >> which is applied to an input stream is known as extraction operator. 
This is discussed in detail here.

Unformatted Input
NameDescription
streamsize gcount() Returns the number of characters read by the last unformatted read operation.

The following member functions of basic_istream change the value:
get(), getline(), ignore(), read(), readsome().

The following functions set value to zero:
putback(), unget(), peek(),operator>>(basic_streambuf*)

Example
    istringstream src ("   hello, world! ");
    ostringstream dst;
    
    src.get(*(dst.rdbuf()));

    //prints:17
    cout << src.gcount() << endl;

    //prints:"   hello, world! "
    cout << quoted(dst.str()) << endl;
  1. int_type get() 
  2. basic_istream& get (char_type& ch) 
  3. basic_istream& get (char_type* s, streamsize n) 
  4. basic_istream& get (char_type* s, streamsize n, char_type d) 
  5. basic_istream& get (basic_streambuf& sb) 
  6. basic_istream& get (basic_streambuf& sb, char_type d)
After constructing the sentry object noskipws = true and doing preliminary checks and actions, extracts characters from the stream,as unformatted input.
  1. Extracts a single character from the stream and returns it.
  2. Extracts a single character from the stream and assigns the character to ch. 
  3. Extracts characters from the stream and stores them in s as a c-string, until either (n-1) characters have been extracted or '\n' is encountered; If  so, it's not extracted and stored. 
  4. Extracts characters from the stream and stores them in s as a c-string, until either (n-1) characters have been extracted or delimiter d is encountered; If  so, it's not extracted and stored. 
  5. Extracts all the characters from the stream and inserts them into the stream buffer object sb. 
  6. Extracts all the characters from the stream and inserts them into the stream buffer object sb. Extraction is stopped when delimiter d is encountered; if so, it's not extracted and stored.
A null character ('\0') is automatically appended to the written sequence if n is greater than zero, even if an empty string is extracted.
The number of characters successfully read and stored by this function can be accessed by calling member gcount.
    Example
    istringstream src (R"( The quick brown fox 
    jumps over 
    #the lazy dog  
    and feels as if be were in seventh #heaven)");
    ostringstream dst;
    string str(30,0);
    
    //1
    int i;
    //i:32
    i = src.get();
    
    //2
    char c;
    //c:T
    src.get(c);
    
    //3
    src.get(str.data(),30);
    //prints:"he quick brown fox "
    cout << quoted(str) << endl;
    
    //4
    src.get(str.data(),30,'#');
    //prints:"\njumps over \n"
    cout << quoted(str) << endl;
    
    //5
    src.get(*dst.rdbuf());
    //prints:"#the lazy dog  "
    cout << quoted(dst.str()) << endl;
    
    //6
    dst.str("");
    src.get(*dst.rdbuf(),'#');
    //prints:"\nand feels as if be were in seventh "
    cout << quoted(dst.str()) << endl;
    1. basic_istream& getline
      (char* s, streamsize n ) 
    2. basic_istream& getline
      (char* s, streamsize n, char d)
    After constructing the sentry object noskipws = true and doing preliminary checks and actions, extracts characters from the stream,as unformatted input.
    1. Extracts characters from the stream and stores them in s as a c-string, until either (n-1) characters have been extracted or '\n' is encountered; If so, it's extracted and discarded. 
    2. Extracts characters from the stream and stores them in s as a c-string, until delimiter d is encountered; if so, it's extracted and discarded.
    A null character ('\0') is automatically appended to the written sequence if n is greater than zero,even if an empty string is extracted.
    The number of characters successfully read and stored by this function can be accessed by calling member gcount.
    Example
    istringstream src (R"( The quick brown fox 
    jumps over 
    #the lazy dog  
    and feels as if be were in seventh #heaven)");
    string str(30,0);
    
    
    //1
    src.getline(str.data(),30);
    //prints:" The quick brown fox "
    cout << quoted(str) << endl;
    
    //2
    str.assign(30,0);
    src.getline(str.data(),30,'#');
    //prints:"jumps over \n"
    cout << quoted(str) << endl;
    istream& ignore
    (streamsize n = 1, int d= EOF)
     After constructing the sentry object noskipws = true and doing preliminary checks and actions, extracts characters from the stream,as unformatted input.

    Extracts characters from the stream until either (n-1) characters have been extracted or delimiter d is encountered; if so, it's extracted.
    If EOF is encountered, extraction will also stop and eof bit is set.
    All the extracted characters are discarded.

    The number of characters extracted but discarded by this function can be accessed by calling member gcount.
      Example
      string instr = R"( The quick brown fox 
      jumps over 
      #the lazy dog  
      and feels as if be were in seventh #heaven)";
      istringstream src (instr);
      
      int p=0;
      src.ignore(30);
      //prints:" The quick brown fox \njumps ov"
      cout << quoted(instr.substr(p,src.gcount())) << endl;
      
      p+=src.gcount();
      src.ignore(40,'#');
      //prints:"er \n#"
      cout << quoted(instr.substr(p,src.gcount())) << endl;
      
      p+=src.gcount();
      src.ignore(60);
      //prints:"the lazy dog  \nand feels as if be were in seventh #heaven"
      cout << quoted(instr.substr(p,src.gcount())) << endl;
      int peek()After constructing the sentry object noskipws = true and doing preliminary checks and actions, extracts characters from the stream,as unformatted input.

      Returns the next character in the input sequence, without extracting it: The character is left as the next character to be extracted from the stream.

      Calling this function sets the value returned by gcount to zero.

      Example
      istringstream src (" The quick brown fox ");
      int i;
      //i:32
      i = src.peek();
      istream& read
      (char* s, streamsize n)
      After constructing the sentry object noskipws = true and doing preliminary checks and actions, extracts characters from the stream,as unformatted input.

      Extracts n characters from the stream and stores them in the array pointed to by s. This function simply copies a block of data, without checking its contents nor appending a null character at the end.

      The number of characters read by this function can be accessed by calling member gcount.

      Example
      istringstream src (R"( The quick brown fox 
      jumps over 
      #the lazy dog  
      and feels as if be were in seventh #heaven)");
      ostringstream dst;
      string str(50,0);
      

      src.read(str.data(),40);
      //prints:" The quick brown fox \njumps over \n#the l"
      cout << quoted(str) << endl;
      streamsize  readsome
      (char* s, streamsize n)
      After constructing the sentry object noskipws = true and doing preliminary checks and actions, extracts characters from the stream,as unformatted input.

      Extracts up to n characters from the stream and stores them in the array pointed by s, stopping as soon as the internal buffer kept by the associated stream buffer object (if any) runs out of characters, even if the end-of-file has not yet been reached.

      The function is meant to be used to read data from certain types of asynchronous sources that may eventually wait for more characters, since it stops extracting characters as soon as the internal buffer is exhausted, avoiding potential delays.

      Note that this function relies on internals of the particular stream buffer object associated to the stream whose behavior is mostly implementation-defined for standard classes.

      The function returns the number of characters read which can also be accessed by calling member gcount.

      Example
      istringstream src (R"( The quick brown fox 
      jumps over 
      #the lazy dog  
      and feels as if be were in seventh #heaven)");
      ostringstream dst;
      string str(50,0);
      

      //ret:40
      auto ret = src.readsome(str.data(),40);
      //prints:" The quick brown fox \njumps over \n#the l"
      cout << quoted(str) << endl;
      istream& unget()After constructing the sentry object noskipws = true and doing preliminary checks and actions, extracts characters from the stream,as unformatted input.

      Attempts to decrease the current location in the stream by one character, making the last character extracted from the stream once again available to be extracted by input operations.
      Works even if eofbit is set.
      Calling this function sets the value returned by gcount to zero.

      Example
      istringstream src ("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
      
      //ch:A
      auto ch = static_cast<char>(src.get());
      
      src.unget();
      
      //ch:A
      ch = static_cast<char>(src.get());
      basic_istream& putback
      (char_type ch )
      After constructing the sentry object noskipws = true and doing preliminary checks and actions, extracts characters from the stream,as unformatted input.
      Clears eof bit if it's set.
      Puts the character ch back to the input stream so the next extracted character will be ch.
      If this does not match the character at the put back position, the behavior depends on the particular stream buffer object associated to the stream and its implementation.

      Calling this function sets the value returned by gcount to zero.

      Example
      istringstream src ("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
      
      //ch:A
      auto ch = static_cast<char>(src.get());
          
      src.putback('a');
      
      //ch:?
      ch = static_cast<char>(src.get());
      
      src.clear();
      
      //ch:B
      ch = static_cast<char>(src.get());
      
      src.putback('B');
          
      //ch:B
      ch = static_cast<char>(src.get());

      Positioning
      NameDescription
      1. istream& seekg
        (streampos pos)
      2. istream& seekg
        (streamoff off,  ios_base::seekdir dir)
      After constructing the sentry object noskipws = true and doing preliminary checks and actions, extracts characters from the stream,as unformatted input.
      The function clears the eofbit flag, if set before the call. Negative offsets are allowed.
      1. Sets the position of the next character to be extracted from the input stream to pos from the absolute beginning of the stream (ios_base::beg).
      2. Sets the position of the next character to be extracted from the input stream to off relative to dir. The constants are defined ios_base class.
      Calling this function does not alter the value returned by gcount.
      streampos tellg()After constructing the sentry object noskipws = true and doing preliminary checks and actions, extracts characters from the stream,as unformatted input.
      Returns the current position of the extractable character from the stream.
      Works even if eofbit is set.
      Calling this function does not alter the value returned by gcount.
      Example
      istringstream src ("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
      
      src.seekg(10);
      //ch:K
      auto ch = static_cast<char>(src.peek());
      //p:10
      auto p = src.tellg();
          
      src.seekg(-10, ios_base::end);
      //ch:Q
      ch = static_cast<char>(src.peek());
      //p:16
      p = src.tellg();
      
      src.seekg(5, ios_base::beg);
      //ch:F
      ch = static_cast<char>(src.peek());
      //p:5
      p = src.tellg();

      Other
      NameDescription
      int sync()After constructing the sentry object noskipws = true and doing preliminary checks and actions, extracts characters from the stream,as unformatted input.
      Synchronizes the input buffer with the associated data source.
      It's implementation specific. In some implementations,  the input buffer removes any unread character from the stream.
      Returns 0 on success and 1 on failure.

      Example
      void file_abc()
      {
          std::ofstream f("test.txt");
          f << "abc\n";
      }
       
      void file_123()
      {
          std::ofstream f("test.txt");
          f << "123\n";
      }
       
          file_abc(); 
          f.open("test.txt");
          //c:a
          f >> c;
          file_123(); 
          f.sync();
          //c:2
          f >> c;
          //c:3
          f >> c;

      No comments:

      Post a Comment