350 likes | 613 Views
C++ Standard Library strings. Libraries File I/O C++ string functions Class vector Algorithms Field Width Format Flags. Libraries. #include < iostream > - defines I/O functions Instance of istream : cin – standard input Instances of ostream : cout – standard output
E N D
C++ Standard Library strings • Libraries • File I/O • C++ string functions • Class vector • Algorithms • Field Width • Format Flags
Libraries • #include <iostream> - defines I/O functions • Instance of istream: • cin – standard input • Instances of ostream: • cout – standard output • #include <fstream> - for file processing • #include <iomanip> - for formatting
Libraries • #include <string.h> • for C style string functions • #include <string> • for C++ style string class and functions • #include <vector> • for the vector class (a vector is a type of array) • #include <algorithm> • for the sort() function, and other algorithms
Stream Input Classes & Objects • The istream class supports stream-input operations • The predefined object cin is an instance of the istream class • Connected to the standard input device (usually the keyboard) • cin >> x; //data “flows” in the directions of the arrows //to the right
Stream Output Classes & Objects • The ostream class supports stream-onput operations • The predefined object cout is an instance of the ostream class • Connected to the standard output device (usually the computer screen) • cout << x; //data “flows” in the directions of the arrows //to the left
File Input • Syntax for file input: ifstreamobject(inputfile) • makes an ifstream object (variable) for file input ifstreamfileInputStream("input.txt"); • If the file cannot be opened, the ifstreamobject is NULL if(NULL==fileInputStream) { cout << "Cannot open file " << endl; //quit program return 1; }
File Input • 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 • Function getline(x, y) reads a line from input stream x into C++ style string y string line; //C++ style string while(!fileInputStream.eof()) { getline(fileInputStream, line); //output to screen cout<<line<<endl; }
File Output • Syntax for file input: ofstreamobject(outputfile) • makes an ofstreamobject (variable) for file output ofstreamfileOutputStream("output.txt"); • If the file cannot be opened, the ofstreamobject is NULL if(NULL==fileOutputStream) { cout << "Cannot open file " << endl; //quit program return 1; }
File Output • When writing to a file, use the ofstreamobject (variable) in place of cout string line; //C++ style string while(!fileInputStream.eof()) { getline(fileInputStream, line); //write to output file fileOutputStream<<line<<endl; //output to screen cout<<line<<endl; } • See example file at: getline.cpp
C++ Strings • C++ strings are an array of characters with many built-in functions • String initialization: string sentence = "This is a string."; • Can use the subscript operator [ ] to access each character cout<<sentence[0]<<endl; //T
Function find() • The find(x) function returns the index of the start of the matching string x string sentence = "This is a string."; cout<<"sentence.find(\"is\") = "<<sentence.find("is")<<endl; //sentence.find("is") = 2
Function length() • Function length()will return the number of characters in the string string sentence = "This is a string."; cout<<"sentence.length() = "<<sentence.length()<<endl; //17
Function substr() • The function substr(pos,len)returns a substring, starting at character position pos and spans lencharacters string sentence = "This is a string."; intlength = sentence.length(); //17 cout<<sentence.substr(0,length/2)<<endl; //This is cout<<sentence.substr(length/2,length); //a string.
STL • Standard Template Library (STL) • Also called the C++ Standard Library • Has template-based classes • Implements many common data structures and algorithms • Three components of STL • Containers • Iterators • Algorithms
Containers • Common data structures written as a template class • Three types • Sequence containers • Associative containers • Container adapters • First class containers • Sequence & associative containers • Have certain member functions that container adapters do not have
Sequence Containers • Linear data structures • vector • Rapid insertions & deletions at back • Direct access to any element • deque • Rapid insertions & deletions at front or back • Direct access to any element • list • Doubly-linked list • Rapid insertions & deletions anywhere
Associative Containers • Contain key–value pairs • set • Rapid lookup, no duplicates allowed • multiset • Rapid lookup, duplicates allowed • map • One to one mapping, rapid key-based lookup, no duplicates allowed • multimap • One to one mapping, rapid key-based lookup, duplicates allowed
Container Adapters • stack • Last-in-first-out • queue • First-in-first-out • priority_queue • Highest priority element is always the first element out
Member Functions • Common member functions for all STL containers • Default constructor, copy constructor, destructor • Each container has several overloaded constructors • empty() • True if no elements in container; false otherwise • size() • Number of elements in the container • operator= • Assigns one container to another
Member Functions II • operator< • True if 1st container is less than the 2nd container • Otherwise returns false • operator<=, >, >=, ==, != • True if 1st is <=, >, >=, ==, or != 2nd • Otherwise returns false • swap • Swaps the elements of two containers
Header Files <vector> <list> <deque> <queue> (has queue & priority_queue) <stack> <map> (has map & multimap) <set> (has set & multiset) <bitset>
Iterators • Iterators similar to pointers • Used to point to elements of 1st class containers • Operators • Dereferencing operator (*) • Dereferences an iterator, so you can use the element to which it points • Increment operator (++) • Moves the iterator to the next element of the container
Iterators II • Operators • 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 • Iterator objects • iterator points to an element that can be modified • const_iterator points to a constant element
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 • Can use the subscript operator [ ], as well as the at( ) member function • Use function push_back() to add elements to the end of the vector object • function size() returns the number of elements • See examplevector.cpp
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> ... sort(v2.begin(), v2.end());
Field Width • Number of character positions in input or output • cout<<setw(n) • N is the field width • Otherwise fill characters are inserted as padding • If the value has more character than N, the full number or character string will be printed
Field Width /*see width.cpp*/ #include <iostream> #include <iomanip> using namespace std; int main(){ cout.width(5); cout<<123<<endl; // 123 cout<<setw(5)<<123456<<endl; //123456 return 0; }
Format Flags • Various format flags to control formatting • Controlled by member functions: • cout.setf(ios::??) – set a format • cout.unsetf(ios::??) – unset a format • cout.flags(ios::??) – set format • Or by parameterized stream manipulators: • cout<<setiosflags(ios::??) – set a format • cout<<resetiosflags(ios::??) – unset a format
Format Flags • ios::right – right justification • ios::left – left justification • ios::internal • Number’s sign is left-justified • Number’s magnitude is right-justified
Format Flags • See example code at: format.cpp • ios::scientific – scientific notation • ios::uppercase • hex numbers, e in scientific notation become uppercase • ios::showpos • show “+” for positive numbers
Format Flags float originalFormat = cout.flags(); int d = 12345; cout<<setw(10)<<d<<setw(10)<<d<<endl; // 12345 12345 cout<<setiosflags(ios::left); cout<<setw(10)<<d<<setw(10)<<d<<endl; //12345 12345 cout<<setiosflags(ios::internal|ios::showpos); cout<<setw(10)<<d<<endl; //+ 12345
Format Flags cout.fill('$'); cout<<setw(10)<<d<<endl; //+$$$$12345 cout<<setfill('*')<<setw(10)<<d<<endl; //+****12345 cout<<resetiosflags(ios::showpos); cout<<setfill(' ')<<setw(10)<<d<<endl; // 12345 cout<<setiosflags(ios::showbase); cout<<hex<<12345<<endl; //0x3039 cout<<setiosflags(ios::scientific|ios::uppercase); cout<<123.456<<endl; //1.234560E+002
Boolean Format • Use stream manipulator "boolalpha" to display "bool" values as strings ("true" or "false") • Use "noboolalpha" to display as integers (0 or 1) /*see bool.cpp*/ #include<iostream> using namespace std; int main(){ bool b = true; cout<<"b="<<boolalpha<<b<<endl; //b=true cout<<"b="<<noboolalpha<<b<<endl; //b=1 return 0; }