Sharif University of Technology C Programming Languages Lecturer

  • Slides: 87
Download presentation
Sharif University of Technology C++ Programming Languages Lecturer: Omid Jafarinezhad Fall 2013 Lecture 3

Sharif University of Technology C++ Programming Languages Lecturer: Omid Jafarinezhad Fall 2013 Lecture 3 Department of Computer Engineering 1

Outline • Differences between C and C++ • Extensions to C • Namespaces •

Outline • Differences between C and C++ • Extensions to C • Namespaces • String • IOStreams (input, output, file) • Function (template, inline) 2

Differences between C and C++ • Strict type checking // Ok in C ,

Differences between C and C++ • Strict type checking // Ok in C , Error in C ++ int main() { // Error : printf undeclared printf("Hello Worldn"); } // Ok in C++ #include <stdio. h> int main() { printf("Hello Worldn"); } int main() { // Error in C++: return-statement with no value, in function returning 'int' // Error in C++: return; } // Ok in C++ int main() { } 3

Extensions to C • Function Overloading #include <stdio. h> void show(int val) { printf("Integer:

Extensions to C • Function Overloading #include <stdio. h> void show(int val) { printf("Integer: %dn", val); } show void show(double val) { printf("Double: %lfn", val); } show void show(char const *val) { printf("String: %sn", val); } show int main() { show(12); 12 show(3. 1415); 3. 1415 show("Hello World!n"); "Hello World!n" } 4

Extensions to C • Function Overloading: – Do not use function overloading for functions

Extensions to C • Function Overloading: – Do not use function overloading for functions doing conceptually different tasks – C++ does not allow identically named functions to differ only in their return values 5

Extensions to C • Default function arguments #include <stdio. h> int Sum(int a =

Extensions to C • Default function arguments #include <stdio. h> int Sum(int a = 1, int b = 4) {return a + b; } = 1 = 4 int main() { printf("%d", Sum()); // arguments: 1 + 4 Sum() printf("%d”, Sum(20)); // arguments: 20 + 4 Sum(20) printf("%d", Sum(20, 5)); // arguments: 20 + 5 Sum(20, 5) // Sum(, 6); // Error } 6

Extensions to C • Default function arguments – Default arguments must be known at

Extensions to C • Default function arguments – Default arguments must be known at compiletime since at that moment arguments are supplied to functions. Therefore, the default arguments must be mentioned at the function's declaration, rather than at its implementation: // sample header file extern void two_ints(int a = 1, int b = 4); = 1 = 4 // code of function in, filename. ccp void two_ints(int a, int b) {. . . } 7

Differences between C and C++ • NULL-pointers , nullptr ( NULL-pointers 0 -pointers and

Differences between C and C++ • NULL-pointers , nullptr ( NULL-pointers 0 -pointers and 0 -pointers nullptr C++ 11) #include <stdio. h> void show(int val) { printf("Integer: %dn", val); } show void show(double val) { printf("Double: %lfn", val); } show void show(char const *val) { printf("String: %sn", val); } show int main() { show(0); show(NULL); // show( 0); NULL show((char *)0); (char *)0 show(nullptr); // in C++ 11 nullptr } 8

Differences between C and C++ • The void parameter list #include <stdio. h> void

Differences between C and C++ • The void parameter list #include <stdio. h> void show(); show int main() { show(10); } C ( ) C++ ( ) void show( show int val) { printf("Integer: %dn", val); } val 9

Differences between C and C++ • The void parameter list #include <stdio. h> void

Differences between C and C++ • The void parameter list #include <stdio. h> void show( show void); void C ( ) C++ ( ) int main() { show(10); // Error too many arguments to function } void show( show int val) { printf("Integer: %dn", val); } val 10

Differences between C and C++ • Defining local variables #include <stdio. h> int main()

Differences between C and C++ • Defining local variables #include <stdio. h> int main() { for (int i = 0; i < 20; ++i) int i = 0 printf("%dn", i); switch (int c = getchar()) int c = getchar() { . . } if (int c = getchar()) …. int c = getchar() } 11

Differences between C and C++ • typedef – The keyword typedef is still used

Differences between C and C++ • typedef – The keyword typedef is still used in C++, but is not required anymore when defining union, struct or enum definitions. enum struct Some. Struct { int a; double d; char string[80]; }; Some. Struct what; // in c : c struct Some. Struct what; what. d = 3. 1415; 12

Extensions to C • The scope resolution operator : : #include <stdio. h> int

Extensions to C • The scope resolution operator : : #include <stdio. h> int counter = 50; // global variable int main() { int counter = 10; counter = 10 for (int counter = 1; // this refers to the counter = 1 counter < 10; // local variable counter++) { printf("%dn", : : counter // global variable // divided by counter); // local variable } } 13

Extensions to C • cout, cerr cout cin, and cin – cout, analogous to

Extensions to C • cout, cerr cout cin, and cin – cout, analogous to stdout cout – cin, analogous to stdin cin – cerr, analogous to stderr cerr 14

Extensions to C #include <iostream> using namespace std; int main() { int ival; char

Extensions to C #include <iostream> using namespace std; int main() { int ival; char sval[30]; std: : cout << "Enter a number: n"; // <<, insertion operator std: : cout cin >> ival; // >>, extraction operator cin cout << "And now a string: n"; cout cin >> sval; cin cout << "The number is: " << ival << "n" "And the string is: " << sval << 'n'; 'n' } 15

Extensions to C • Functions as part of a struct /* in C ++

Extensions to C • Functions as part of a struct /* in C ++ */ struct Person { char name[80]; char address[80]; void print(); }; void Person: : print() { cout << "Name: " << name << "n" "Address: " << address << "n"; } Person person; strcpy(person. name, "Karel"); person. print(); /* in C and C++*/ typedef struct { char name[80]; char address[80]; } PERSON; /* print information */ void print(PERSON const *p){…} /* etc. . */ 16

Extensions to C • References – the reference operator & indicates that ref is

Extensions to C • References – the reference operator & indicates that ref is not & itself an int but a reference to one – synonyms for variables – A reference to a variable is like an alias // c++ int_value; int &ref = int_value; // c and c++ int_value; int *ref = &int_value; ++ref; ++int_value; ++(*ref); 17

Extensions to C • References // c++ void increase(int &valr) { valr += 5;

Extensions to C • References // c++ void increase(int &valr) { valr += 5; } // c and c++ void increase(int *valp) { *valp += 5; } int main() { int x; increase(x); } int main() { int x; increase(&x); &x } 18

Extensions to C • References extern int *ip; extern int &ir; extern ip =

Extensions to C • References extern int *ip; extern int &ir; extern ip = 0; // reassigns ip, now a 0 -pointer ir = 0; // ir unchanged, the int variable it refers to is now 0 int &q; // Error : declared as reference but not initialized &q; Error : 19

Extensions to C • References could result in extremely ugly code int &func() {

Extensions to C • References could result in extremely ugly code int &func() { static int value; return value; } int main() { func() = 20; func() += func(); } 20

Extensions to C • Rvalue References (C++11) – lvalue reference ( typename &) lvalue

Extensions to C • Rvalue References (C++11) – lvalue reference ( typename &) lvalue typename & – rvalue references ( typename &&) rvalue int. Val() { return 5; } int &ir = int. Val(); // fails: refers to a temporary int const &ic = int. Val(); // OK: immutable temporary int *ip = &int. Val(); // fails: no lvalue available 21

Extensions to C • Rvalue References (C++11) void receive(int &value) // note: lvalue reference

Extensions to C • Rvalue References (C++11) void receive(int &value) // note: lvalue reference { cout << "int value parametern"; } void receive(int &&value) // note: rvalue reference { cout << "int R-value parametern"; } int main() { receive(18); // int R-value parameter 18 int value = 5; receive(value); // int value parameter value receive(int. Val()); // int R-value parameter int. Val() } 22

Memory leak #include <stdlib. h> void function_which_allocates(void) { /* allocate an array of 45

Memory leak #include <stdlib. h> void function_which_allocates(void) { /* allocate an array of 45 floats */ float * a = malloc(sizeof(float) * 45); /* additional code making use of 'a' */ /* return to main, having forgotten to free the memory we malloc'd */ } int main(void) { function_which_allocates(); /* the pointer 'a' no longer exists, and therefore cannot be freed, but the memory is still allocated. a leak has occurred. */ } 23

Extensions to C • Memory leak struct Data { char *text; size_t size; size_t

Extensions to C • Memory leak struct Data { char *text; size_t size; size_t void copy(Data const &other) { text = strdup(other. text); size = strlen(text); } }; Data data. Factory(char const *txt) { Data ret = {strdup(txt), strlen(txt)}; return ret; } int main() { Data d 1 = {strdup("hello"), strlen("hello")}; Data d 2; d 2. copy(d 1); Data d 3; d 3. copy(data. Factory("hello")); } 24

Extensions to C • Rvalue References (C++11) struct Data { // …. void copy(Data

Extensions to C • Rvalue References (C++11) struct Data { // …. void copy(Data &&other) { text = other. text; other. text = 0; } }; Data data. Factory(char const *txt) { Data ret = {strdup(txt), strlen(txt)}; return ret; } int main() { Data d 1 = {strdup("hello"), strlen("hello")}; Data d 2; d 2. copy(d 1); Data d 3; d 3. copy(data. Factory("hello")); } 25

Extensions to C • Strongly typed enumerations (C++11) enum class Safe. Enum { NOT_OK,

Extensions to C • Strongly typed enumerations (C++11) enum class Safe. Enum { NOT_OK, // 0, by implication OK = 10, MAYBE_OK // 11, by implication }; enum class Char. Enum : unsigned char enum class { NOT_OK, OK }; // Char. Enum: : OK 26

Extensions to C • enumerations in c and c++ #include <iostream> using namespace std;

Extensions to C • enumerations in c and c++ #include <iostream> using namespace std; enum Color { RED, // 0 BLUE // 1 }; enum Fruit { BANANA, // 0 APPLE // 1 }; int main() { Color a = RED; RED Fruit b = BANANA; BANANA // The compiler will compare a and b as integers if (a == b) // and find they are equal! cout << "a and b are equal" << endl; else cout << "a and b are not equal" << endl; return 0; } 27

Extensions to C • Strongly typed enumerations (C++11) #include <iostream> using namespace std; enum

Extensions to C • Strongly typed enumerations (C++11) #include <iostream> using namespace std; enum class Color { RED, // 0 BLUE // 1 }; enum class Fruit { BANANA, // 0 APPLE // 1 }; int main() { Color a = Color: : RED; Color: : RED Fruit b = Fruit: : BANANA; Fruit: : BANANA /* compile error here, as the compiler doesn't know how to compare different types Color and Fruit */ if (a == b) cout << "a and b are equal" << endl; else cout << "a and b are not equal" << endl; return 0; } 28

Extensions to C • Type inference: auto and decltype (C++11) auto variable = 5;

Extensions to C • Type inference: auto and decltype (C++11) auto variable = 5; // int x = 4; auto d = 2. 5; // d will be type double auto z = d; // z will be type double auto w = "hi"; // w will be type const char* decltype(5) x; // x will be type int because 5 is an int decltype(x) y = 6; // y will be type int because x is an int auto z = x; // z will type int auto int multiply (int x, int y){…} auto multiply (int x, int y) -> int{…} 29

Extensions to C • function declaration using auto (C++11) #include <iostream> #include <string> //

Extensions to C • function declaration using auto (C++11) #include <iostream> #include <string> // simple function with a default argument, returning nothing void f 0(const std: : string& arg = "world") { int main() std: : cout << "Hello, " << arg << 'n'; { } f 0(); // function returning a pointer to f 0, (C++11 style) fp 11()("test"); auto fp 11() -> void(*)(const std: : string&) { auto fp 11() -> void(*)(const std: : string&) fp 03()("again"); return f 0; } } // output // c and c++ (pre-C++11 style) Hello, world // function returning a pointer to f 0 Hello, test void (*fp 03())(const std: : string&) { void (*fp 03())(const std: : string&) Hello, again return f 0; } 30

Extensions to C • Range-based for-loops (C++11) struct Big. Struct { double array[100]; int

Extensions to C • Range-based for-loops (C++11) struct Big. Struct { double array[100]; int last; }; // assume int array[30] for (auto &element: array) statement Big. Struct data[100]; // assume properly initialized elsewhere int count. Used() { int sum = 0; // const &: the elements aren't modified for (auto const &element: data) sum += element. last; return sum; } 31

Extensions to C • binary constant – e. g. int i = 0 b

Extensions to C • binary constant – e. g. int i = 0 b 101; 0 b • data types – void, char, short, int, long, float and double – bool, bool wchar_t, long and long double wchar_t – char 16_t and char 32_t char 16_t – size_t ( size_t typedef long unsigned int size_t) size_t 32

Extensions to C • Bool b. Value; // true (!=0) or false (0) bool

Extensions to C • Bool b. Value; // true (!=0) or false (0) bool b. Value 1 = true; // explicit assignment bool b. Value 2(false); // implicit assignment bool b. Value 1 = !true; // b. Value 1 will have the value false bool b. Value 2(!false); // b. Value 2 will have the value true bool b. Value = true; // bool b. Value = 30; cout << b. Value << endl; // 1 endl cout << !b. Value << std: : endl; // 0 std: : endl if (!b. Value) cout << "The if statement was true" << endl; else cout << "The if statement was false" << endl; 33

Extensions to C • The static_cast conversion – static_cast<type>(expression); int x = 19; int

Extensions to C • The static_cast conversion – static_cast<type>(expression); int x = 19; int y = 4; sqrt(x / y); sqrt(static_cast<double>(x) / y); • The dynamic_cast conversion • The const_cast conversion • The reinterpret_cast conversion 34

Namespaces • Defining namespaces // in file 1. cpp namespace Cpp. NS { double

Namespaces • Defining namespaces // in file 1. cpp namespace Cpp. NS { double cos(double arg. In. Degrees) { . . . } } // in file 2. cpp namespace Cpp. NS { double sin(double arg. In. Degrees) { . . . } } // same as file 3. ccp namespace Cpp. NS { double cos(double arg. In. Degrees) { . . . } double sin(double arg. In. Degrees) { . . . } } 35

Namespaces • Referring to namespaces #include <file 3> file 3 #include <iostream> #include <cmath>

Namespaces • Referring to namespaces #include <file 3> file 3 #include <iostream> #include <cmath> cmath using namespace std; // same as file 3. ccp namespace Cpp. NS { double cos(double arg. In. Degrees) { … } double sin(double arg. In. Degrees) { … } } int main() { cout << "The cosine of 60 degrees is: " << Cpp. NS: : cos(60) << : : cos(60); : : cos(60) // call the standard std: : cos(60) function } 36

Namespaces • Referring to namespaces #include <file 3> file 3 #include <iostream> #include <cmath>

Namespaces • Referring to namespaces #include <file 3> file 3 #include <iostream> #include <cmath> cmath using namespace std; // same as file 3. ccp namespace Cpp. NS { double cos(double arg. In. Degrees) { … } double sin(double arg. In. Degrees) { … } } int main() { using Cpp. NS: : cos; /*. . . */ cout << cos(60) // calls Cpp. NS: : cos() cos(60) << // call the standard std: : cos(60) function : : cos(60); : : cos(60) } 37

Namespaces • The standard namespace – The std namespace is reserved by C++ std

Namespaces • The standard namespace – The std namespace is reserved by C++ std namespace – The standard defines many entities that are part of the runtime available software • e. g. , cout, cout cin, cin cerr • the templates defined in the Standard Template Library • the Generic Algorithms 38

Namespaces • Nesting namespaces #include <file 3> file 3 int main() { Cpp. NS:

Namespaces • Nesting namespaces #include <file 3> file 3 int main() { Cpp. NS: : value = 0; Cpp. NS: : Virtual: : pointer = 0; } #include <file 3> file 3 using namespace Cpp. NS; int main() { value = 0; Virtual: : pointer = 0; } // same as file 3. ccp namespace Cpp. NS { int value; namespace Virtual { void *pointer; } } 39

Namespaces • Nesting namespaces #include <file 3> file 3 using namespace Cpp. NS; using

Namespaces • Nesting namespaces #include <file 3> file 3 using namespace Cpp. NS; using namespace Virtual; int main() { value = 0; pointer = 0; } #include <file 3> file 3 using namespace Cpp. NS : : Virtual; int main() { Cpp. NS : : value = 0; pointer = 0; } // same as file 3. ccp namespace Cpp. NS { int value; namespace Virtual { void *pointer; } } 40

Namespaces • Namespace aliasing #include <file 3> file 3 namespace CV = Cpp. NS:

Namespaces • Namespace aliasing #include <file 3> file 3 namespace CV = Cpp. NS: : Virtual; int main() { CV: : pointer = 0; } #include <file 3> file 3 namespace CV = Cpp. NS: : Virtual; using namespace CV; int main() { pointer = 0; } // same as file 3. ccp namespace Cpp. NS { int value; namespace Virtual { void *pointer; } } 41

Namespaces • Defining entities outside of their namespaces #include <file 3> namespace Cpp. NS

Namespaces • Defining entities outside of their namespaces #include <file 3> namespace Cpp. NS { namespace Virtual { void *pointer; typedef int INT 8[8]; INT 8 *squares(); } } // out side the namespace such as in cpp file Cpp. NS: : Virtual: : INT 8 * Cpp. NS : : Virtual: : squares() { /* … */ } namespace Cpp. NS { namespace Virtual { void *pointer; typedef int INT 8[8]; INT 8 *squares() { /* … */ } } } 42

String • std: : string public class string { /* … */ string& string:

String • std: : string public class string { /* … */ string& string: : operator= (const string& str); string& string: : assign (const string& str); string& string: : operator= (const char* str); string& string: : assign (const char* str); string& string: : operator= (char c); /* … */ } #include <iostream> #include <string> using namespace std; int main() { string s. String; s. String = string("One"); cout << s. String << endl; // One const string s. Two("Two"); s. String. assign(s. Two); cout << s. String << endl; // Two s. String = "Three"; // Assign a C-style string cout << s. String << endl; // Three s. String. assign("Four"); cout << s. String << endl; // Four s. String = '5'; // Assign a char cout << s. String << endl; // 5 string s. Other; // Chain assignment s. String = s. Other = "Six"; cout << s. String << " " << s. Other << endl; // Six } 43

String • std: : string assignment and swapping const string s. Source("abcdefg"); string s.

String • std: : string assignment and swapping const string s. Source("abcdefg"); string s. Dest; s. Dest. assign(s. Source, 2, 4); assign cout << s. Dest << endl; s. Dest. assign("abcdefg", 4); assign cout << s. Dest << endl; s. Dest. assign(4, 'g'); assign cout << s. Dest << endl; // cdef // abcd // gggg string s. Str 1("red"); string s. Str 2("blue); cout << s. Str 1 << " " << s. Str 2 << endl; swap(s. Str 1, s. Str 2); cout << s. Str 1 << " " << s. Str 2 << endl; s. Str 1. swap(s. Str 2); swap cout << s. Str 1 << " " << s. Str 2 << endl; // red blue // blue red // red blue 44

String • std: : string inserting #include <iostream> #include <string> using namespace std; int

String • std: : string inserting #include <iostream> #include <string> using namespace std; int main() { string s. String("aaaa"); s. String("aaaa") cout << s. String << endl; // aaaa s. String. insert(2, string("bbbb")); insert cout << s. String << endl; // aabbbbaa s. String. insert(4, "cccc"); insert cout << s. String << endl; // aabbccccbbaa const string s. Insert("01234567"); // insert substring of s. Insert from index [3, 7) into s. String at index 2 s. String. insert(2, s. Insert, 3, 4); // aa 3456 bbccccbbaa insert cout << s. String << endl; } 45

String • std: : string appending string s. String("one"); s. String += string(" two");

String • std: : string appending string s. String("one"); s. String += string(" two"); // s. String += " two"; string s. Three(" three"); s. String. append(s. Three); append cout << s. String << endl; // one two three string s. String("one "); const string s. Temp("twothreefour"); // append substring of s. Temp starting at index 3 of length 5 s. String. append(s. Temp, 3, 5); append cout << s. String << endl; // one three 46

String • std: : string Member functions – http: //en. cppreference. com/w/cpp/string/basic_string at clear

String • std: : string Member functions – http: //en. cppreference. com/w/cpp/string/basic_string at clear insert erase compare replace substr copy find rfind_first_of find_last_of /* … */ access specified character with bounds checking clears the contents inserts characters removes characters compares two strings replaces specified portion of a string returns a substring copies characters find characters in the string find the last occurrence of a substring find first occurrence of characters find last occurrence of characters 47

String • std: : string Member functions – http: //en. cppreference. com/w/cpp/string/basic_string/at #include <stdexcept>

String • std: : string Member functions – http: //en. cppreference. com/w/cpp/string/basic_string/at #include <stdexcept> #include <iostream> int main() { std: : string s("message"); // for capacity abx s = "abc"; string size = 3 s. at(2) = 'x'; // ok string capacity = 7 std: : cout << s << 'n'; basic_string: : at std: : cout << "string size = " << s. size() << 'n'; s. size() std: : cout << "string capacity = " << s. capacity() << 'n'; s. capacity() try { // throw, even if capacity allowed to access element s. at(3) = 'x'; } catch (std: : out_of_range& exc) { std: : cout << exc. what() << 'n‘; } } 48

String • std: : string Convert from strings – C++11 added several string conversion

String • std: : string Convert from strings – C++11 added several string conversion functions stoi stol stoul stoll stoull stof stod stold Convert string to integer Convert string to long int Convert string to unsigned integer Convert string to long Convert string to unsigned long Convert string to float Convert string to double Convert string to long double int stoi (const string& str, size_t* idx = 0, int base = 10); std: : string str_bin = "-10010110001"; int i_bin = std: : stoi (str_bin, nullptr, 2); std: : stoi std: : cout << str_bin << ": " << i_bin; // -10010110001: -1201 49

IOStreams • Input/output in C++ – istream class, extraction operator (>>) – ostream class,

IOStreams • Input/output in C++ – istream class, extraction operator (>>) – ostream class, insertion operator (<<) #include <iostream> using namespace std; int main() { cout << "Enter your age: " << endl; endl // print text to the monitor int n. Age; cin >> n. Age; // get input from the user if (n. Age <= 0) { // print an error message cerr << "Oops, you entered an invalid age!" << endl; return 1; } cout << "You entered " << n. Age << " years old" << endl; return 0; } 50

IOStreams • extraction operator (>>) char buf[10]; cin >> buf; // what happens if

IOStreams • extraction operator (>>) char buf[10]; cin >> buf; // what happens if the user enters 18 characters? /* * C++ provides a manipulator known as setw (in the iomanip. h header) that can * be used to limit the number of characters read in from a stream. */ #include <iomanip. h> char buf[10]; cin >> setw(10) >> buf; setw(10) /* Any remaining characters will be left in the stream until the next extraction */ 51

IOStreams • extraction operator (>>) /* The one thing that we have omitted to

IOStreams • extraction operator (>>) /* The one thing that we have omitted to mention so far is that the extraction operator works with “formatted” data — that is, it skips whitespace (blanks, tabs, and newlines) */ char ch; while (cin >> ch) input : Hello my name is Omid cout << ch; output: Hellomynameis. Omid while (cin. get(ch)) get cout << ch; input : Hello my name is Omid output : Hello my name is Omid 52

IOStreams • extraction operator (>>) char str. Buf[11]; // only read the first 10

IOStreams • extraction operator (>>) char str. Buf[11]; // only read the first 10 characters cin. get(str. Buf, 11); input : Hello my name is Omid get cout << str. Buf << endl; output : Hello my n /* One important thing to note about get() is that it does not read in a newline character! This can cause some unexpected results */ char str. Buf[11]; cin. get(str. Buf, 11); input : Hello! � get cout << str. Buf << endl; output : Hello cin. get(str. Buf, 11); get cout << str. Buf << endl; /* Consequently, getline() like get() but reads the newline as well */ 53

IOStreams • extraction operator (>>) /* If you need to know how many character

IOStreams • extraction operator (>>) /* If you need to know how many character were extracted by the last call of getline(), use gcount() */ char str. Buf[100]; cin. getline(str. Buf, 100); cout << str. Buf << endl; cout << cin. gcount() << " characters were read" << endl; cin. gcount() // A special version of getline() for std: : string str. Buf; getline(cin, str. Buf); cout << str. Buf << endl; 54

IOStreams • insertion operator (<<) /* To switch a flag on, use the setf()

IOStreams • insertion operator (<<) /* To switch a flag on, use the setf() function To turn a flag off, use the unsetf() function */ cout. setf(ios: : showpos); // turn on the ios: : showpos flag setf(ios: : showpos) cout << 27 << endl; // output : +27 cout. unsetf(ios: : showpos); // turn off the ios: : showpos flag unsetf(ios: : showpos) cout << 28 << endl; // output : 28 cout. setf(ios: : showpos | ios: : uppercase); ios: : showpos | ios: : uppercase // basefield : “oct”, “dec”, and “hex” cout. unsetf(ios: : dec); // turn off decimal output ios: : dec cout. setf(ios: : hex); // turn on hexadecimal output ios: : hex cout << 27 << endl; // output : 1 b cout << hex << 27 << endl; cout << 28 << endl; cout << dec << 29 << endl; // print 27 in hex : 1 b // we're still in hex : 1 c // back to decimal: 29 55

IOStreams • insertion operator (<<) cout << true << " " << false <<

IOStreams • insertion operator (<<) cout << true << " " << false << endl; cout. setf(ios: : boolalpha); cout << true << " " << false << endl; cout << noboolalpha << true << " " << false << endl; cout << boolalpha << true << " " << false << endl; // 0 1 // true false cout << fixed << endl; // Use decimal notation for values cout << setprecision(3) << 123. 456 << endl; // 123. 456 setprecision(3) cout << setprecision(4) << 123. 456 << endl; // 123. 4560 setprecision(4) 56

IOStreams • insertion operator (<<) showpos noshowpos fixed scientific showpoint noshowpoint noshowpoin setprecision(int) internal

IOStreams • insertion operator (<<) showpos noshowpos fixed scientific showpoint noshowpoint noshowpoin setprecision(int) internal left right setfill(char) setw(int) fill(char) width(int) Prefixes positive numbers with a + Doesn’t prefix positive numbers with a + Use decimal notation for values Use scientific notation for values Show a decimal point and trailing 0′s for floating-point values Don’t show a decimal point and trailing 0′s for floating-point values Sets the precision of floating-point numbers (iomanip. h) Returns the current precision of floating-point numbers Sets the precision of floating-point numbers and returns old precision Left-justifies the sign of the number, and right-justifies the value Left-justifies the sign and value Right-justifies the sign and value Sets the parameter as the fill character (iomanip. h) Sets the field width for input and output to the parameter (iomanip. h) Returns the current fill character Sets the fill character and returns the old fill character Returns the current field width Sets the current field width and returns old field width 57

IOStreams • insertion operator (<<) cout << -12345 << endl; cout << setw(10) <<

IOStreams • insertion operator (<<) cout << -12345 << endl; cout << setw(10) << -12345 << endl; setw(10) cout << setw(10) << left << -12345 << endl; cout << setw(10) << right << -12345 << endl; cout << setw(10) << internal << -12345 << endl; cout. fill('*'); cout << -12345 << endl; cout << setw(10) << left << -12345 << endl; cout << setw(10) << right << -12345 << endl; cout << setw(10) << internal << -12345 << endl; // print default value with no field width // print default with field width // print left justified // print right justified // print internally justified -12345 - 12345 -12345 ****-12345****-12345 -****12345 58

IOStreams • Stream classes for strings – One of the primary uses of string

IOStreams • Stream classes for strings – One of the primary uses of string streams is to buffer output for display at a later time, or to process input line-by-line #include <sstream> sstream stringstream os; os << "en garde!" << endl; os << "en garde!" << endl // set the stringstream buffer to "en garde!“ os. str("en garde!"); // set the stringstream buffer to "en garde!“ str("en garde!") cout << os. str(); os. str() os. str(""); os. str(std: : string()); os. clear(); // erase the buffer os << "12345 67. 89"; // insert a string of numbers into the stream string str. Value; int n. Value; os >> str. Value; double d. Value; string str. Value 2; os >> n. Value >> d. Value; os >> str. Value 2; cout << str. Value << " - " << str. Value 2 << endl; // 12345 - 67. 89 59

IOStreams • Stream states (Flags) • Operations on streams may fail for various reasons.

IOStreams • Stream states (Flags) • Operations on streams may fail for various reasons. Whenever an operation fails, further operations on the stream are suspended. It operation fails, further operations on the stream are suspended is possible to inspect, set and possibly clear the condition state of streams, allowing a program to repair the problem rather than having to abort. ios: : goodbit Everything is okay (none of the other three condition flags) ios: : badbit Some kind of fatal error occurred (eg. the program tried read past the end of a file) ios: : eofbit The stream has reached the end of a file ios: : failbit A non-fatal error occurred (eg. the user entered letters when the program was letters expecting an integer) expecting an integer 60

IOStreams • Stream states - Member function good() Returns true if the goodbit is

IOStreams • Stream states - Member function good() Returns true if the goodbit is set bad() Returns true if the badbit is set eof() Returns true if the eofbit is set fail() Returns true if the failbit is set clear() Clears all flags and restores the stream to the goodbit clear(state) Clears all flags and sets the state flag passed in rdstate() Returns the currently set flags setstate(state) Sets the state flag passed in 61

IOStreams • Stream states - Member function void state() { cout << cin. bad()

IOStreams • Stream states - Member function void state() { cout << cin. bad() cin. fail() << cin. fail() cin. eof() << cin. eof() cin. good() << 'n'; cin. good() } int main() { /* Whenever an operation string line; fails, further operations on the int x; stream are suspended */ cin >> x; // omid � state(); // 0100 // cin. clear(); cin >> line; // suspended cin >> line; // omid state(); // 0100 state(); // 0001 getline(cin, line); // suspended getline(cin, line); // � state(); // 0100 state(); // 0001 } 62

IOStreams • Stream states if (cin) // if (not cin. fail()) if (cin >>

IOStreams • Stream states if (cin) // if (not cin. fail()) if (cin >> x) // if (not (cin >> x). fail()) if (getline(cin, str)) // if (not getline(cin, str). fail()) 63

IOStreams • Input validation Function Return value --------------------------------------------------------isalnum(int) non-zero if the input is a

IOStreams • Input validation Function Return value --------------------------------------------------------isalnum(int) non-zero if the input is a letter or a digit isalpha(int) non-zero if the input is a letter iscntrl(int) non-zero if the input is a control character isdigit(int) non-zero if the input is a digit isgraph(int) non-zero if the input is printable character that is not whitespace isprint(int) non-zero if the input is printable character (including whitespace) ispunct(int) non-zero if the input is neither alphanumeric nor whitespace isspace(int) non-zero if the input is whitespace isxdigit(int) non-zero if the input is a hexadecimal digit (0 -9, a-f, A-F) 64

IOStreams • Input validation cout << "Enter your age: "; string str. Age; cin

IOStreams • Input validation cout << "Enter your age: "; string str. Age; cin >> str. Age; // Check to make sure each character is a digit for (unsigned int n. Index=0; n. Index < str. Age. length(); n. Index++) if (!isdigit(str. Age[n. Index])) isdigit(str. Age[n. Index]) { …. } 65

Your practice: run it int n. Age; string str; while (1) { cout <<

Your practice: run it int n. Age; string str; while (1) { cout << "Enter your age: "; cin >> n. Age; // user enter the following : 23 dncdlklkd if (cin. fail()) // no extraction took place { cin. clear(); // reset the state bits back to goodbit so we can use ignore() cin. ignore(1000, 'n'); // clear out the bad input from the stream continue; // try again } cin. ignore(1000, 'n'); // clear out any additional input from the stream if (n. Age <= 0) // make sure n. Age is positive continue; cin >> str; break; } 66

IOStreams • File – ifstream (derived from istream) ifstream • file input – ofstream

IOStreams • File – ifstream (derived from istream) ifstream • file input – ofstream (derived from ostream) ofstream • output file – fstream (derived from iostream). fstream • input/output file – fstream. h 67

IOStreams • File output #include <fstream> #include <iostream> // ofstream is used for writing

IOStreams • File output #include <fstream> #include <iostream> // ofstream is used for writing files. // We'll make a file called Sample. dat ofstream outf("Sample. dat"); // If we couldn't open the output file stream for writing if (!outf) // Print an error and exit { … } // We'll write two lines into this file outf << "This is line 1" << endl; outf << << endl outf << "This is line 2" << endl; 68

IOStreams • Output File – ifstream returns a 0 if we’ve reached the end

IOStreams • Output File – ifstream returns a 0 if we’ve reached the end of the file (EOF) #include <fstream> #include <iostream> // ifstream is used for reading files // We'll read from a file called Sample. dat ifstream inf("Sample. dat"); // If we couldn't open the output file stream for writing if (!inf) // Print an error and exit { … } // While there's still stuff left to read while (inf) { // read stuff from the file into a string and print it std: : string str. Input; inf >> str. Input; getline(inf, str. Input); cout << str. Input << endl; }c 69

IOStreams • fstream : input/output file app ate binary in nocreate noreplace out trunc

IOStreams • fstream : input/output file app ate binary in nocreate noreplace out trunc Opens the file in append mode only be used in streams open for output-only operations Seeks to the end of the file before reading/writing Opens the file in binary mode (instead of text mode) Opens the file in read mode (default for ifstream) Opens the file only if it already exists Opens the file only if it does not already exist Opens the file in write mode (default for ofstream) Erases the file if it already exists // Note we have to specify both in and out because we're using fstream iofile("Sample. dat", ios: : in | ios: : out); ofstream myfile; myfile. open ("example. bin", ios: : out | ios: : app | ios: : binary); 70

IOStreams #include <fstream> #include <iostream> // ofstream is used for writing files. // We'll

IOStreams #include <fstream> #include <iostream> // ofstream is used for writing files. // We'll make a file called Sample. dat ofstream myfile ("Sample. dat", ios: : app); if (myfile. is_open()) { // We'll write two lines into end of file outf << "This is line 1" << endl; outf << "This is line 2" << endl; myfile. close(); } else cout << "Unable to open file"; 71

IOStreams • open/close file ofstream outf("Sample. dat"); outf << "This is line 1" <<

IOStreams • open/close file ofstream outf("Sample. dat"); outf << "This is line 1" << endl; outf << "This is line 2" << endl; outf. close(); // explicitly close the file // … outf. open("Sample. dat", ios: : app); outf << "This is line 3" << endl; outf. close(); 72

IOStreams • get and put stream pointers • tellg() and tellp() – These two

IOStreams • get and put stream pointers • tellg() and tellp() – These two member functions have no parameters and return a value of the member type pos_type, which is an integer data type representing the current position of the get stream pointer (in the case of tellg) or the put stream pointer (in the case of tellp) • seekg() and seekp() – These functions allow us to change the position of the get and put stream pointers 73

IOStreams • get and put stream pointers beg cur end The offset is relative

IOStreams • get and put stream pointers beg cur end The offset is relative to the beginning of the file (default) The offset is relative to the current location of the file pointer The offset is relative to the end of the file ifstream inf("Sample. dat"); inf. seekg(14, ios: : cur); // move forward 14 bytes seekg(14, ios: : cur) inf. seekg(-18, ios: : cur); // move backwards 18 bytes seekg(-18, ios: : cur) inf. seekg(22, ios: : beg); // move to 22 nd byte in file inf. seekg(24); // move to 24 th byte in file seekg(24) // move to the 28 th byte before end of the file inf. seekg(-28, ios: : end); seekg(-28, ios: : end) 74

IOStreams • get and put stream pointers long begin, end; ifstream myfile ("example. txt");

IOStreams • get and put stream pointers long begin, end; ifstream myfile ("example. txt"); begin = myfile. tellg(); myfile. seekg (0, ios: : end); end = myfile. tellg(); myfile. close(); cout << "size is: " << (end-begin) << " bytes. n"; (end-begin) 75

Dynamic memory allocation • new and delete int n. Size = 12; int *pn.

Dynamic memory allocation • new and delete int n. Size = 12; int *pn. Array = new int[n. Size]; pn. Array[4] = 7; delete[] pn. Array; delete /////////////// void do. Something() { int *pn. Value = new int; // Memory leaks } /////////////// int *pn. Value = new int; // dynamically allocate an integer delete pn. Value; // pn. Value not set to 0 if (pn. Value) *pn. Value = 5; // will cause a crash 76

IOStreams // reading a complete binary file #include <iostream> #include <fstream> using namespace std;

IOStreams // reading a complete binary file #include <iostream> #include <fstream> using namespace std; ifstream: : pos_type size; char * memblock; int main () { ifstream file ("example. bin", ios: : in|ios: : binary|ios: : ate); if (file. is_open()) { if (file. is_open()) size = file. tellg(); memblock = new char [size]; file. seekg (0, ios: : beg); file. read (memblock, size); file. close(); cout << "the complete file content is in memory“; delete[] memblock; } else cout << "Unable to open file"; return 0; } 77

Handling errors • assert statement int g_an. Array[10]; // a global array of 10

Handling errors • assert statement int g_an. Array[10]; // a global array of 10 characters int Get. Array. Value(int n. Index) { // use if statement to detect violated assumption if (n. Index < 0 || n. Index > 9) return -1; // return error code to caller return -1; return g_an. Array[n. Index]; } int main() { Get. Array. Value(10); return 0; } 78

Handling errors • assert statement #include <cassert> // for assert() using namespace std; int

Handling errors • assert statement #include <cassert> // for assert() using namespace std; int g_an. Array[10]; // a global array of 10 characters int Get. Array. Value(int n. Index) { // we're asserting that n. Index is between 0 and 9 assert(n. Index >= 0 && n. Index <= 9); // this is line 7 in Test. cpp return g_an. Array[n. Index]; } int main() { Get. Array. Value(10); // error in line 7 … return 0; } 79

Inline functions int min(int n. X, int n. Y) { return n. X >

Inline functions int min(int n. X, int n. Y) { return n. X > n. Y ? n. Y : n. X; } int main() { using namespace std; cout << min(5, 6) << endl; min(5, 6) cout << min(3, 2) << endl; min(3, 2) return 0; } 80

Inline functions inline int min(int n. X, int n. Y) { return n. X

Inline functions inline int min(int n. X, int n. Y) { return n. X > n. Y ? n. Y : n. X; } /* Now when the program compiles main(), it will create machine code as if main() had been written like this: */ int main() { using namespace std; cout << (5 > 6 ? 6 : 5) << endl; (5 > 6 ? 6 : 5) cout << (3 > 2 ? 2 : 3) << endl; (3 > 2 ? 2 : 3) return 0; } 81

Function templates int max. F(int n. X, int n. Y) { return (n. X

Function templates int max. F(int n. X, int n. Y) { return (n. X > n. Y) ? n. X : n. Y; } double max. F(double d. X, double d. Y) { return (d. X > d. Y) ? d. X : d. Y; } // … 82

Function templates // this is the template parameter declaration template < template typename Type>

Function templates // this is the template parameter declaration template < template typename Type> Type max. F( Type d. X, Type d. Y) Type { return (d. X > d. Y) ? d. X : d. Y; } // … int n. Value = max. F(3, 7); // returns 7 int double d. Value = max. F(6. 34, 18. 523); // returns 18. 523 double max. F(6. 34, 18. 523); char ch. Value = max. F('a', '6'); // returns 'a‘ char max. F('a', '6'); int n 2 = max. F<int>(3, 7); // returns 7 double d 2 = max. F<int>(6. 34, 18. 523); // returns 18 83

Function templates template<typename T> void f(T s) { std: : cout << s <<

Function templates template<typename T> void f(T s) { std: : cout << s << 'n'; } int main() { f<double>(1); // instantiates and calls f<double>(double) f<>('a'); // instantiates and calls f<char>(char) f(7); // instantiates and calls f<int>(int) } 84

Function templates // this is the template parameter declaration template < template typename T,

Function templates // this is the template parameter declaration template < template typename T, typename U> T max(T d. X, U d. Y) { return (d. X > d. Y) ? d. X : d. Y; } // … int n. Value = max(3, 7); // returns 7 int double d. Value = max(6. 34, 18. 523); double max(6. 34, 18. 523); // returns 18. 523 char ch. Value = max('a', '6'); // returns 'a' char max('a', '6'); 85

Function templates // return type depends on template parameters template < template typename T,

Function templates // return type depends on template parameters template < template typename T, typename U> auto add(T t, U u) -> decltype(t + u) { // … } return t + u; 86

Reference • http: //en. cppreference. com/w/ • http: //www. cplus. com/reference/ 87

Reference • http: //en. cppreference. com/w/ • http: //www. cplus. com/reference/ 87