STL STREAMS, STRINGS



1 - Streams

Communication between different components in a computer
istreams, ostreams

//Heading
#include<iostreams>

Also possible: using namespace :: std;



1-1 Stream objects and operators

Objects:
Type
Name

Effect
istream
cin
Reads input from the standars input channel
ostream
cout
Writes output to the standard output channel
ostream
cerr
Writes error messages to the error output channel
ostream
clog
Writes log messages to the standard logging channel
wistream
wcin
Reads wide-character input from the standars input channel
wostream
wcout
Writes wide-character output to the standard output channel
wostream
wcerr
Writes wide-character to the error output channel
wostream
wclog
Writes wide-character log to the standard logging channel


Operators: ">>" and "<<"


1-2 State of Streams

Identify whether I/O was successful, and if not, the reason of the failure

Constants
Constant
Meaning
goodbit
Everithing is OK
eofbit
End-of-file was encountered
failbit
Error; an I/O operation was not successful
badbit
Fatal error


!!! These constant are not defined globally; don't forget the scope operator ios::  (see examples) !!!


1-2-1 Functions accessing the state of Streams

Function
Meaning
good( )
Returns true if the stream is OK (ie: if goodbit is set)
eof( )
Returns true if end-of-file was hit (ie: eofbit is set)
fail( )
Returns true if an error has occured (ie: failbit or badbit is set)
bad( )
Returns true if a fatal error has occured (ie: badbit is set)
rdstate( )
Returns the currently set flags
clear( )
Clears all flags
clear(state)
Clears all sets state flags
setstate(state)
Sets additional state flags



Example: Check whether failbit is set in a stream called strm, and clear it if ncecessary.

// Check whether failbit is set; "&" means "and"
if (strm.rdstate( ) & ios::failbit){
    cout << "failbit is set" << endl;
}

// Clear failbit if it is set
strm.clear(failbit);





// Other way to check whether failbit is set
if (strm.fail( ) & ! strm.bad( ) ){
    cout << "failbit is set" << endl;
}



// Other way to clear failbit; "~" means "everithing but"
strm.clear(strm.rdstate( ) & ~ ios::failbit);



Exercise: Ask a user to enter an integer. Then, display "Your entry is OK", followed by the number he has entered if his entry is OK; if it is not, display "Failure " if  his entry has failed in the sense of failbit, or "Fatal error" if his entry has leaded to a fatal error.

Answer:

// Heading
#include <iostream>
using namespace std;


int main ( )
{
 
  // Declaration
  int a;

 
// Asking for the user to enter an integer
  cout << "Enter an integer: ";
  cin >> a;

  
// Check whether everything is OK
  if (cin.good( ) ){
      cout << "Your entry is OK: " << a << endl;

  }
  else {

      // Check whether failbit is set
      if (cin.fail( ) & ! cin.bad( ) ){
      cout << "Failure" << endl;
      }
      else {
             
cout << "Fatal error" << endl;
      }

  }

 }



1-2-2 Stream State in Bolean conditions

// Check whether a stream is OK
if (strm);

// Check whether a stream is not OK
if (! strm);


Exercise: Ask a user to enter an integer. Display "Your entry is OK", followed by the number he has entered if his entry is OK, and repeat the process; if it is not, display "Failure", and stop the code.

Answer:

// Heading
#include <iostream>
using namespace std;


int main ( )
{
 
    // Declaration
    int a;
 
    // Ask for the user to enter an integer
    cout << "Enter an integer: ";

    // Check whether the entry is OK and cycle if it is
    while (cin >> a) {
       
cout << "Your entry is OK: " << a << endl;
   
    cout << "Enter an integer: ";
    }
   
    // Display "Failure" as soon as the entry has failed
    cout << "Failure" << endl;

}


1-3 Pre-defined Manipulators

Modify a stream


1-3-1 Pre-defined Manipulators with no argument

Manipulator

Effect
endl
Output '\n' and flushes the output buffer
flush
flushes the output buffer
ws
Reads and discard whitespaces
uppercase
All the characters are written as uppercase
nouppercase All the characters are written with no uppercase
dec
Converts into base 10
hex
Converts into base 16
oct
Converts into base 8
fixed
Using floating point format
scientific
Using scientific format


!!! Don't use parentheses !!!


1-3-2 Pre-defined Manipulators with arguments

// Additional heading
#include<iomanip>

Manipulator

Effect
setbase (n)
Output integers in base b (b must be 8, 10 or 16)
setprecision (n) Rounds of n digits after decimal point




1-3-3 Exercises

Exeample 1:
Write a code that asks a user to enter an integer, a base, and displays the integer translated into this base. (remember to check the entries).

Answer:

// Heading
#include <cstdlib>
#include <iostream>
#include<iomanip>
using namespace std;

int main ( )
{
 
    // Declaration
    int a,base;

   
// Asking for the user to enter an integer
    cout << "Enter an integer in base 10: ";
    cin >> a;

    // Exit if cin is not OK
    if (cin.fail( ) ){
      cerr << "Error while reading the integer"  << endl;
      return EXIT_FAILURE;
    }
 
    // Asking for the user to enter a base
    cout << "Enter a base: ";
    cin >> base;

   // Exit if cin is not OK
   if (cin.fail( ) ){
      cerr << "Error while reading the base"  << endl;
      return EXIT_FAILURE;
   }
 
   
// Exit if the base is incorrect
   if ((base!=8)&&(base!=10)&&(base!=16)){
      cerr << "Base differs from 8, 10 and 16"  << endl;
      return EXIT_FAILURE;
   }

   // Display a in the selected base
   cout  << setbase (base) << a << endl;

}

Rmq: What happens when adding the command line: cout << 20 at the end of the code ?


Example 2:

Answer:

// Heading
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;

int main ( )
{
 
    // Declaration
    double x;

   
// Asking for the user to enter a real number
    cout << "Enter a real number: ";
    cin >> x;

    // Exit if cin is not OK
    if (cin.fail( ) ){
      cerr << "Error while reading the real number"  << endl;
      return EXIT_FAILURE;
    }

   
// Display x with 4 digits
    cout << setprecision(4)  << x << endl;  /* Replace this line with
                                                                                             cout << setprecision(4) << scientific << x << endl;
                                                                                             for the second code */

}




2 - Strings


 
Kind of vectors having  the "char" type

Algorithms can be used for strings

//Heading
#include<string>


2-1 Iterators
//Declaration
string :: iterator pos;

Accept the same arguments than containers iterators: begin( ), end( ), rbegin( ), rend( ) ...



2-2 Operations

Create/destroy operations
Operation
Effect

string s
Creates an empty string s
string s (str) Creates a string s that is the copy of the existing string str
string s (str,str_idx) Creates a string s with the values of the existing string str starting with index str_idx
string s(str,str_idx,str_len) Creates a string s with the values of the existing string str starting with index str_idx, but having at most str_len elements
strings s (num,c) Creates a string s initialized with num occurences of the character c
strings s (beg,end)
Creates a string s initialized with all the characters in the range [beg,end)
s.clear( )
makes s empty


Nonmodifying operations
Operation

Effect
s.capacity( ), s.lenght( )
Returns the maximum possible number of elements without reallocation
s.reserve(my_value)
Enlarges capacity, if not enough yet
s.max_size( )
Returns the maximum number of characters a string may contain
s.empty( )
Returns whether the string s is empty
s.find (charac)
returns the first occurence of value
s.find (charac,idx) returns the first occurence of value starting from index idx
s.rfind (charac) returns the first occurence of value in the reverse order
s.find_first_of (charac) finds the first character that is part of charac
s.find_last_of (charac) finds the last character that is part of charac
s.find_first_not_of (charac) finds the first character that is not part of charac
s.find_last_not_of (charac) finds the last character that is not part of charac
s.substr( )
returns s
s.substr(idx) returns the range starting from idx (included) to the end of s; s.substr( ) returns s
s.substr(N,idx) returns the N values of s starting from index idx



Element access
Operation

Effect
s.at(idx)
Returns the element with index idx (throws range exception if idx is out of range)
s[idx]
Returns the element with index idx with no range checking

The second operation has different behavors when applied to const, or normal string:
Example:

const string cs ("hello");
string s ("bye");

s[2];   // yields 'y'
s.at(2); yields 'y'

s[100]; // yields an error
s.at(100); // yields out_of_range

s[s.lenght( )]; // yields error
cs[cs.lenght( )]; // yields a value generated by the default constructor, usually '\O'


Comparisons:
==, !=, <, >
s.compare(str) returns 0 if s equals str, a negative integer if s<str, a positive integer if s>str


Modifying operations
Operation

Effect
s.assign(str)
Assigns s with the string str
s.assign(str,idx1,idx2) Assigns s with the values in the range [idx1,idx2] in string str
s1.swap(s2) Swap s1 and s2
s.append(str)
Appends str to s
s.append(str,idx1,idx2) Appends the elements in the range[idx1,idx2] of str to s
s.append(N,charac) Appends N times the character charac
s.insert(posi,str)
Inserts str at position posi
s.replace(idx1,idx2,str) Replaces the range [idx1,idx2] in s with str (str does not have necessarily the same  lenght than [idx1,idx2]
s.erase(idx) Erases all the elements in s starting from index idx (including idx)
s.erase(N,idx) Erases the N values starting with idx (including idx)


Concatenation: s1 + s2
example:
"standard" + "ization"; // returns "standardization"

2-3 Exercise
Declare 4 empty strings s1, s2, s3, s4. Assign s1 and s2 with "How old are you ?", assign s3 with "I'm fine", and s4 with "are you ?" (by using the function assign and s1).
Display s1 directly. Display s1 by using an iterator.
Withdraw " old" from s2.
Assign s3 with
"How old are you ? I'm fine.", by using a concatenation with s1.
Insert "Who " at the begining of s4.
Reverse s4.


Answer:


3 - File Streams: basic principles


// Heading
#include<fstream>

3-1 ifstream

Goal: reading from files

//Opening
ifstream unit_name ("file_name", ios :: in);

!!! "file_name" is a char* !!!

//Closing
unit_name.close();

//Read from a file opened with the unit unit_name
unit_name >> my_variable;

3-2 ofstream
Goal: write into files

//opening
ofstream unit_name ("file_name",ios :: arg);
// where arg=out if you want to create/overwrite a file
named "file_name"
// or arg=app if you want the buffer to be positioned at the end of the (already existing) file "file_name"

// Other way foe creating a file
ofstream out("file_name");



//Closing
unit_name.close();

//Write into a file opened with the unit unit_name
unit_name <<  my_value;


 
4- String Streams

Streams allow to read from strings and write into strings.

//Heading
#include<sstream>


4-1 String Stream classes

            //Declaration
           istringstream :: my_istringstream;


            //Declaration
           ostringstream :: my_ostringstream;


            //Declaration
           stringstream :: my_stringstream;


4-2 Common basic functions

Operation

Effect
ssg.str( )
Returns the buffer as a string
ssg.str(string_val) Sets the contents of the buffer as a_string_val


4-3 Exercise

Ask a user to enter a list of real numbers, one after one, while storing these values into a vector (these number may represent a sequence of instants the user has to plot a solution).

When the user has finished to enter his list, he types any character, amd then, for each real number, create a file having for name "solution_" followed with the real number round with a presision 4 (these files may be devoted to be filled with the values of a numerical solution at times t = real_number).

Each of this file must be writen the real number.

Answer: