Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ics212-28-strings-stl-file-io

 ics212-28-strings-stl-file-io

Avatar for William Albritton

William Albritton

November 12, 2015
Tweet

More Decks by William Albritton

Other Decks in Programming

Transcript

  1. Memory Allocation  C++ File I/O  C++ string functions

     C++ Standard Template Library (STL)  C++ Formatting
  2. Libraries for I/O  #include <iostream> - defines I/O functions

     Instance of istream: cin for standard input  Instances of ostream: cout for standard output  #include <fstream> - for file processing
  3. Stream Input Classes and Objects  The istream class supports

    stream-input operations  Predefined object cin is an instance of the istream class  Connected to the standard input device, which is usually the keyboard  Data “flows” in the directions of the arrows to the right cin >> variable1;
  4. Stream Output Classes and Objects  The ostream class supports

    stream-output operations  Predefined object cout is an instance of the ostream class  Connected to the standard output device, which is usually the computer screen  Data “flows” in the directions of the arrows to the left cout << variable1;
  5. File Input Stream  Syntax for file stream: ifstream object(inputfile)

     Makes an ifstream object (variable) for file stream  If the file cannot be opened, the ifstream object is NULL ifstream fileInputStream(inputFile); if(NULL==fileInputStream) { cout<<“Cannot open file”<<endl; return 1; //quit program }
  6. End of File  When reading from a file, use

    eof() function to check for the end of the file  Returns nonzero (true) when reach the end of the file, and zero (false) otherwise
  7. Read from a File  Function getline(x, y) reads a

    line from input stream x into C++ style string y string line = “line”; //C++ style string while(!fileInputStream.eof()) { getline(fileInputStream, line); cout<<line<<endl; }
  8. File Output Stream  File input stream syntax: ofstream object(outputfile)

     Makes an ofstream object (variable) for file output stream  If the file cannot be opened, the ofstream object is NULL ofstream fileOutputStream(outputFile); if(NULL==fileOutputStream) { cout<<“Cannot open file”<<endl; return 1; //quit program }
  9. Write to a File  When writing to a file,

    use the ofstream object (variable) in place of cout string line = “line”; //C++ style string while(!fileInputStream.eof()) { getline(fileInputStream, line); //write to a file fileOutputStream<<line<<endl; cout<<line<<endl; //output to screen }
  10. Example Code  For examples of file input and file

    output, see the example program: getline.cpp  In this program, you can enter the input and output files on the commandline, otherwise the program will prompt you for the file names  Try using input file: electricity.txt ./program electricity.txt output.txt
  11. Libraries for Strings  #include <string.h>  For C style

    string functions  #include <string>  For C++ style string class and functions
  12. C++ String Initialization  C++ string initialization syntax: string variable

    = “initial value”;  Similar to C style strings, C++ strings are also stored as an array of characters, so we can use the subscript operator [ ] to access each character string sentence = “This is a string.”; cout<<sentence[0]<<endl; //‘T’
  13. Function find()  The find(x) function returns the index of

    the start of the matching string x  Just like arrays, the 1st index in a string is 0 (zero) string sentence = “This is a string.”; cout<<sentence.find(“is”); //2
  14. Function length()  Function length() will return the number of

    characters in the string string sentence = “This is a string.”; cout<<sentence.length(); //17
  15. Function substr()  Function substr(pos,len) returns a substring, starting at

    character position pos and spans len characters string sentence = “This is a string.”; int length = sentence.length(); //17 cout<<sentence.substr(0,length/2); //“This is ” cout<<sentence.substr(length/2,length); //“a string.”
  16. Standard Template Library (STL)  Also called the C++ Standard

    Library  Has template-based classes  Implements many data structures and algorithms  Three components of STL 1. Containers 2. Iterators 3. Algorithms
  17. Containers  Common data structures written as a template class

     Three types 1. Sequence containers 2. Associative containers 3. Container adapters
  18. Sequence Containers  Linear data structures, so they have a

    front and a back to them  vector  Rapid insertions and deletions at back  Direct access to any element  deque  Rapid insertions and deletions at front or back  Direct access to any element
  19. Sequence Containers  Linear data structures, so they have a

    front and a back to them  list  Doubly-linked list  Rapid insertions and deletions anywhere
  20. Associative Containers  No strict linear order, but data has

    associations with each other  set  Rapid lookup, no duplicates allowed  multiset  Rapid lookup, duplicates allowed
  21. Associative Containers  No strict linear order, but data has

    associations with each other  map  One to one mapping, rapid key-based lookup, no duplicates allowed  multimap  One to one mapping, rapid key-based lookup, duplicates allowed
  22. Container Adapters  Interfaces that limit the functions of a

    base container  For example, a stack is a container adapter that can be implemented as a deque, vector, or list  stack  Last-in-first-out  queue  First-in-first-out  priority_queue  Highest priority element is always the first element out
  23. Header Files  These header files have classes and member

    functions from the C++ Standard Template Library (STL)  #include <vector>  #include <list>  #include <deque>  #include <queue>  #include <stack>  #include <map>  #include <set>  #include <bitset>
  24. STL Member Functions  Common member functions for all STL

    containers:  Each container has several overloaded constructors, including a default constructor, copy constructor, and destructor  size() returns number of elements in the container  empty() returns true if no elements in container; returns false otherwise  swap() swaps the elements of two containers
  25. STL Operators  Common operators for all STL containers: 

    operator=() assigns one container to another  operator<() returns true if 1st operand is less than 2nd operand; otherwise returns false  operators <=, >, >=, ==, and != work in a similar manner as operator<()
  26. Vector Sequence Container  Class vector is a data structure

    with continuous memory locations (an array)  A vector stores elements on the heap, so the size can grow and shrink as needed
  27. Examples with Vector  Instantiate a vector of integers and

    call some functions #include <vector> //vector library //code . . . vector<int> vector1; cout<<vector1.size()<<endl; //0 cout<<boolalpha<<vector1.empty(); //true
  28. Vector Functions  push_back()  Adds elements to the end

    of the vector object vector1.push_back(10); vector1.push_back(20); vector1.push_back(30);
  29. Vector Functions  subscript operator [ ] and at( )

    function  Do the same thing, return the object located at that index for(int i = 0; i<vector1.size(); i++ ){ cout<<vector1[i]<<' '; cout<<vector1.at(i)<<' '; //10 10 20 20 30 30 }
  30. Iterators  Iterators are similar to pointers  Used to

    point to elements of sequence and associative containers  Two kinds of iterator objects  const_iterator: points to a constant element that cannot be modified  iterator: points to an element that can be modified
  31. Iterator Operators  Dereferencing operator (*)  Dereferences an iterator,

    so you can use the value of the element to which it points  Increment operator (++)  Moves the iterator to the next element of the container
  32. Iterator Functions  begin()  Points to the 1st element

    of the container  end()  Points one element past the end of the container  Is used only in an equality or inequity comparisons
  33. Constant Iterator Loop  Loops through a vector, but cannot

    change the elements vector1[0] = 40; //array subscript vector<int>::const_iterator vi; for(vi = vector1.begin(); vi != vector1.end(); vi++ ){ cout<<*vi<<‘ ’; //40 20 30 }
  34. Iterator Loop  Loops through a vector, and can change

    the elements vector<int>::iterator vi2; for(vi2 = vector1.begin(); vi2 != vector1.end(); vi2++ ){ cout<<++(*vi2)<<' '; //41 21 31 }
  35. Algorithms  STL provides generic algorithms that can be used

    in most containers  Around 70 standard algorithms  To sort a vector, use the sort() function from the algorithm library #include <algorithm> //algorithm library //code . . . sort(vector2.begin(), vector2.end());
  36. Field Width  Number of character positions in input or

    output  Use function setw(n), where N is the field width  Fill characters are inserted as padding  If the value has more character than N, the full number or character string will be printed  By default, field width adds extra spaces to the left
  37. Field Width Example Code #include <iomanip> //formatting library //code .

    . . int num = 12345; cout<<setw(10)<<num<<setw(10)<<num<<endl; // 12345 12345
  38. Format Flags with Stream Manipulators  Various format flags to

    control formatting  Controlled by parameterized stream manipulators: //set a format cout<<setiosflags(ios::??); //unset a format cout<<resetiosflags(ios::??);
  39. Format Flags for Justification  ios::right  right justification 

    ios::left  left justification int num = 12345; cout<<setiosflags(ios::left); cout<<setw(10)<<num<<setw(10)<<num<<endl; //12345 12345
  40. Internal Justification and Show Positive  ios::internal  Number’s sign

    is left-justified, magnitude is right-justified  ios::showpos  show “+” for positive numbers cout<<setiosflags(ios::internal|ios:: showpos); cout<<setw(10)<<12345<<endl; //+ 12345
  41. Format Flags for Notation  ios::scientific  scientific notation 

    ios::uppercase  hex numbers, e in scientific notation become uppercase cout<<setiosflags(ios::scientific|ios:: uppercase); cout<<123.456<<endl; //1.234560E+002
  42. Memory Management  C++ File I/O  C++ string functions

     C++ Standard Template Library (STL)  C++ Formatting