1 4/11/2020 NOT FINISHED!! MEMO C++. (STL): Standard Template Lib Mihaela Malita mmalita@anselm.edu http://cplusplus.com // File: program.cpp // Title: Prints integers from 1 to limit #include <iostream> using namespace std; int main ( ) { // always has a main function int limit, count = 0; //declare type of variable cout << "Enter an integer? "; //ask cin >> limit; //read value while (i <= limit) { // counts till 5 cout << i << endl; i++; // or i = i + 1; } // same with a DO do { i = i + 1; // or i++; or i+=1; cout << i << '\n' ; } while (i < limit) ; //condition at the end // same with for for (int i = 1; i <= limit; i++) { cout << i << endl; } return 0; // always if program is correct 0=true } RUN progam.cpp Compile: program.cpp -> program.obj Link: program.obj ->program.exe Execute: >program.exe (independent file) switch (day) { // day is 0..6 case 0: cout << " day is Sunday"; break; case 1: cout << " day is Monday"; break; … default: cout << " Error day not 0-6"; } Type bool, bool b=true; // b is true or false // 0 stands for false. Anything =/= 0 is true // can use int or bool. Always prefer bool! cout << boolalpha << b; // prints true FORMAT #include <iomanip> cout << setiosflags(ios::right) << setprecision(3)<<setw(5) << 7.891 ; isspace(c) ; iscntrl ( c); ispunct( c); isprint( c); CONVERSIONS #include <cstdlib> double atof(const char *ptr) // // prints on 2 columns numbers 1-100 double n= atof("2.3"); //alpha to float for (int i=1 ; i<100 ; i++) { int atoi(const char *ptr) // int k=atoi("23"); cout << i << ( (i % 2)? '\t' : '\n' ); } double strtod(const char * s, char **ptr) \a = beep \t = tab \n = new line getch(); // waits for any character from the keyboard d = strtod("2.3 is a nr", &ptr) d = 2.3 and cout << ptr // print “ is a nr” #include "windows.h" #include <cstring> Sleep(30); // sleeps 30 millisecs char *strcat(s1,s2) strncpy(new_s,old_s,size) Data Types Size Range int strcmp(s1,s2) //0 if s1=s2; n>0 if s1>s2;n<0 else char 0-256 size_t_strlen(const char *s) //length of string int ARRAYS unsigned int 0-6535 ( 2 – 1) const int n=5; // declare const size short int A[n] = {0}; //all elements become 0 long int A[n] ={6,2,1,4,7} //elements take values unsigned long 0char mystring[] = "programming"; //ends '\0' double int B[2][2]= {{1,2},{4,8}}; //initialize matrix 2 x 2 float Compare arrays – element by element MATH #include <cmath> Operations: + , - , /, *, % STRING CLASS sin(0.5) cos(double) tan(double) #include <string> exp(4) pow(3.0 2.0) sqrt(4.0) string s = "I love C"; // string s("I love C"); log(double) log10(double) s = s.append(s); // s-> "I love CI love C" floor(9.3) ceil(9.7) fabs(-8.9) s + = "great"; same as s = s + "great"; RANDOM cin >> s; // reads till blank #include <ctime> //for time() getline(cin.s); // reads till '\n' #include <cstdlib> //for srand()CodeBlocks s.length(); same as s.size(); srand(time (0)); //does not return a value! s1.compare(s2); // s1 > s2 , s1 <s2 or s1 == s2 0<=rand()<=RAND_MAX; s.substr(7,5); // from 7 add 5 from string s Ex ;produce a random 1-6: int die= rand()%6 +1; s1.swap(s2); //changes values s1 with s2 s.empty(); // (s.empty() ? "true" : "false") CHAR CLASS s.find_first_of("love" ); // returns first index char c = 'a' ; s.find_last_of("love" ); char(65)= 'A' ; char(97)= 'a'; // ASCII code s.find("love" ); / /returns int (index) On 1 byte: ASCII code 0-255=pow(2,8)-1 //check if there: if ( s.find(w)< s.length() ) char color []=”blue”; //same as s.replace(x,1, "." ); char color []={'/b', '/l', '/u', '/e', '/0'}; string::npos //last position of sting (till the end) #include <cctype> s.insert(3,s2);// inserts at position 3 string s2 isdigit(c); isalpha(c); isalnum(c); // erase position 30->? islower(c); isupper(c); tolower ( c); tolower (c ); s.erase(30); 2 VECTOR CLASS FROM STL #include <vector> int A[] ={2,3,4,5}; //copy from array A, 3 elements vector <int> V(A,A+3); vector <int> V; //declare V without any size V.push_back(w); V.pop_back(); V.front(); V.back(); V.clear(); V.empty(); V.erase(V.begin() + 2); //erase index = 2 V.erase(Ptr); V.insert(V.begin()+1,7); //inserts 7, V[1] = 7 V.resize(10); // extends size of V V.swap(X); // change values V1 == V2 ; //COMPARE V1 > V2; V1 >=V2; V1 < V2 ; V1 <= V2; #include <algorithm> int k = count(V.begin(),V.end(),5); //counts 5 sort(V.begin(),V.end()) ; //sort ascending order erase( find(V.begin(),V.end(),w)) // finds/erases w f random_shuffle(V.begin(),V.end()); // check if it is there, if reach end then NO if ( find(V.begin(),V.end(),w) == V.end() ) cout << “ not found”; // print using iterator- pointer void print ( vector <int> V ) { for (vector <int>::iterator it = V.begin(); it != V.end() ; p++) { cout << *it < < '\t'; } // prototype template < typename T > void print (vector <T> V); // function template < typename T > void print (vector <T> V) { for (int i = 0; i < V.size(); i++) cout << V[i] << '\t'; } POINTER int n = 5; int * ptr = &n; cout << &n; // 034A26F0 address in RAM cout << *ptr ; // * dereference operator, prints 5 void func ( int x ) { //call by value x = 2 *x; } // does not modify x void func ( int &x ) { //call by reference x = 2 * x; } //modifies x fstream ff ("oscar.txt",ios::out|ios::app|ios::in); OOP-CLASS //File: Pet.h #ifndef PET_H #define PET_H class Pet { private: //data-members FILES #include <fstream> string name; // WRITE: int YOB; //year of birth string filename = "ints.txt"; public: // functions-methods ofstream fout ( filename.data() ); Pet(string s=”noName”, int y=0) { //constructor fout << 2012 ; // write to end of file name=s; YOB=y;} fout.close(); //close stream void setYOB (int n){ //setter // Open a file and append YOB = (n>=2000 && n<2014)? n :0;} int getYOB(){ return YOB; } //getter ofstream fout(filename.data(), ios::app); // READ: when you know the file name void print(){ cout<< name <<’\t’ << YOB ; } ifstream fin( "data.txt”); }; if ( !inFile ) { // check if file exists #endif //File: programPet.cpp cerr << "Unable to open \"data.txt\".\n"; exit( EXIT_FAILURE ); // exit(1) | return 1; #include <iostream> using namespace std; //order is important } while ( !fin.eof() ) { // tests end of file #include "Pet.h" // last include the header file fin >> x; // reads from stream int main () { // sets and prints time Pet X (“Coop”,2010); //declare object cout << x << endl; } fin.close(); //close stream t.setYOB(2011); //instantiates YOB // read a char x including blank: fin.get( x ); t.print(); cout << t.getYOB(); // read a line (till endl): getline(fin,x,'\n'); return 0; fstream fin (f.data(),ios::in); // open for reading } if ( fin.fail() ) { // check if file exists INHERITANCE cout << "\nError"; return -1;} printFile(fin); #include "Pet.h" fin.clear(); // reset eof for next input class Cat : public Pet { //Cat is a Pet in.seekg(0); // move to beginning of file public: // functions-methods printFile(fin); //call Cat(); // constructor - same name void speak(){ cout << "meou";} void printFile( fstream & fin ){ void print(){ Pet::print();} string s; while(! fin.eof() ){ }; // in main() – Cat X; X.setName(“Garfield”); getline(fin,s); X.print(); cout<< s << endl; }} // open for more operations (flags)