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

C ++ Programming Languages

  • Upload
    vito

  • View
    50

  • Download
    0

Embed Size (px)

DESCRIPTION

Sharif University of Technology. C ++ Programming Languages. Lecturer: Omid Jafarinezhad Fall 2013 Lecture 3. Department of Computer Engineering. Outline. Differences between C and C++ Extensions to C Namespaces String IOStreams (input, output, file ) Function (template, inline). - PowerPoint PPT Presentation

Citation preview

Page 1: C ++  Programming Languages

1

C++ Programming Languages

Lecturer: Omid JafarinezhadFall 2013

Lecture 3

Department of Computer Engineering

Sharif University of Technology

Page 2: C ++  Programming Languages

2

Outline• Differences between C and C++

• Extensions to C

• Namespaces

• String

• IOStreams (input, output, file)

• Function (template, inline)

Page 3: C ++  Programming Languages

3

Differences between C and C++• Strict type checking// Ok in C , Error in C ++int main() { // Error : printf undeclared printf("Hello World\n"); }

// Ok in C++#include <stdio.h>int main() { printf("Hello World\n"); }

int main() { // Error in C++: return-statement with no value, in function returning 'int' return;}

// Ok in C++int main() { }

Page 4: C ++  Programming Languages

4

Extensions to C• Function Overloading

#include <stdio.h> void show(int val) { printf("Integer: %d\n", val); }void show(double val) { printf("Double: %lf\n", val); } void show(char const *val) { printf("String: %s\n", val); } int main() {

show(12); show(3.1415); show("Hello World!\n");

}

Page 5: C ++  Programming Languages

5

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.

Page 6: C ++  Programming Languages

6

Extensions to C• Default function arguments

#include <stdio.h>

int Sum(int a = 1, int b = 4) {return a + b;}

int main(){ printf("%d", Sum()); // arguments: 1 + 4 printf("%d”, Sum(20)); // arguments: 20 + 4 printf("%d", Sum(20, 5)); // arguments: 20 + 5 // Sum(,6); // Error}

Page 7: C ++  Programming Languages

7

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

time 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);

// code of function in, filename.ccpvoid two_ints(int a, int b) { ... }

Page 8: C ++  Programming Languages

8

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

#include <stdio.h> void show(int val) { printf("Integer: %d\n", val); }void show(double val) { printf("Double: %lf\n", val); } void show(char const *val) { printf("String: %s\n", val); } int main() {

show(0); show(NULL); // show(0); show((char *)0);

show(nullptr); // in C++ 11}

Page 9: C ++  Programming Languages

9

Differences between C and C++• The void parameter list

#include <stdio.h>

void show();

int main() {

show(10); }

void show(int val) { printf("Integer: %d\n", val); }

C ()C++ ()

Page 10: C ++  Programming Languages

10

Differences between C and C++• The void parameter list

#include <stdio.h>

void show(void);

int main() {

show(10); // Error too many arguments to function}

void show(int val) { printf("Integer: %d\n", val); }

C ()C++ ()

Page 11: C ++  Programming Languages

11

Differences between C and C++• Defining local variables

#include <stdio.h>

int main() {

for (int i = 0; i < 20; ++i) printf("%d\n", i);

switch (int c = getchar()){ ....}if (int c = getchar()) ….

}

Page 12: C ++  Programming Languages

12

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.

struct SomeStruct{ int a; double d; char string[80];};SomeStruct what; // in c : struct SomeStruct what; what.d = 3.1415;

Page 13: C ++  Programming Languages

13

Extensions to C• The scope resolution operator ::

#include <stdio.h>int counter = 50; // global variableint main(){ int counter = 10; for (int counter = 1; // this refers to the counter < 10; // local variable counter++) { printf("%d\n", ::counter // global variable / // divided by counter); // local variable }}

Page 14: C ++  Programming Languages

14

Extensions to C• cout, cin, and cerr

– cout, analogous to stdout

– cin, analogous to stdin

– cerr, analogous to stderr

Page 15: C ++  Programming Languages

15

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

cout << "The number is: " << ival << "\n" "And the string is: " << sval << '\n';}

Page 16: C ++  Programming Languages

16

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.. */

Page 17: C ++  Programming Languages

17

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 int_value;int &ref = int_value;

++int_value; ++ref;

// c and c++int int_value;int *ref = &int_value;

++int_value; ++(*ref);

Page 18: C ++  Programming Languages

18

Extensions to C• References

// c++void increase(int &valr){ valr += 5;}

int main(){ int x; increase(x);}

// c and c++void increase(int *valp) {

*valp += 5;}

int main(){ int x; increase(&x); }

Page 19: C ++  Programming Languages

19

Extensions to C• References

extern int *ip; extern int &ir;

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

Page 20: C ++  Programming Languages

20

Extensions to C• References could result in extremely ugly code

int &func(){ static int value; return value;}

int main(){

func() = 20;func() += func();

}

Page 21: C ++  Programming Languages

21

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

int intVal(){ return 5;}

int &ir = intVal(); // fails: refers to a temporaryint const &ic = intVal(); // OK: immutable temporaryint *ip = &intVal(); // fails: no lvalue available

Page 22: C ++  Programming Languages

22

Extensions to C• Rvalue References (C++11)

void receive(int &value) // note: lvalue reference{ cout << "int value parameter\n";}void receive(int &&value) // note: rvalue reference{ cout << "int R-value parameter\n";}int main(){ receive(18); // int R-value parameter int value = 5; receive(value); // int value parameter receive(intVal()); // int R-value parameter}

Page 23: C ++  Programming Languages

23

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. */}

Page 24: C ++  Programming Languages

24

Extensions to C• Memory leak

struct Data{ char *text; size_t size; void copy(Data const &other) { text = strdup(other.text); size = strlen(text); }};Data dataFactory(char const *txt){ Data ret = {strdup(txt), strlen(txt)}; return ret;}

int main(){ Data d1 = {strdup("hello"), strlen("hello")};

Data d2; d2.copy(d1);

Data d3; d3.copy(dataFactory("hello")); }

Page 25: C ++  Programming Languages

25

Extensions to C• Rvalue References (C++11)

struct Data{ // …. void copy(Data &&other) { text = other.text; other.text = 0; }};Data dataFactory(char const *txt){ Data ret = {strdup(txt), strlen(txt)}; return ret;}

int main(){ Data d1 = {strdup("hello"), strlen("hello")};

Data d2; d2.copy(d1);

Data d3; d3.copy(dataFactory("hello")); }

Page 26: C ++  Programming Languages

26

Extensions to C• Strongly typed enumerations (C++11)

enum class SafeEnum{ NOT_OK, // 0, by implication OK = 10, MAYBE_OK // 11, by implication};

enum class CharEnum: unsigned char{ NOT_OK, OK};

// CharEnum::OK

Page 27: C ++  Programming Languages

27

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; Fruit b = 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;}

Page 28: C ++  Programming Languages

28

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; Fruit b = 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;}

Page 29: C ++  Programming Languages

29

Extensions to C• Type inference: auto and decltype (C++11)

auto variable = 5; // int x = 4;auto d = 2.5; // d will be type doubleauto z = d; // z will be type doubleauto w = "hi"; // w will be type const char*

decltype(5) x; // x will be type int because 5 is an intdecltype(x) y = 6; // y will be type int because x is an intauto z = x; // z will type type int

int multiply (int x, int y){…}auto multiply (int x, int y) -> int{…}

Page 30: C ++  Programming Languages

30

Extensions to C• function declaration using auto (C++11)

#include <iostream>#include <string>

// simple function with a default argument, returning nothingvoid f0(const std::string& arg = "world") { std::cout << "Hello, " << arg << '\n';} // function returning a pointer to f0, (C++11 style)auto fp11() -> void(*)(const std::string&) { return f0;}// c and c++ (pre-C++11 style)// function returning a pointer to f0void (*fp03())(const std::string&) { return f0;}

int main(){ f0(); fp11()("test"); fp03()("again");}// outputHello, world Hello, test Hello, again

Page 31: C ++  Programming Languages

31

Extensions to C• Range-based for-loops (C++11)

struct BigStruct{ double array[100]; int last;};

BigStruct data[100]; // assume properly initialized elsewhere

int countUsed(){ int sum = 0; // const &: the elements aren't modified for (auto const &element: data) sum += element.last; return sum;}

// assume int array[30]for (auto &element: array) statement

Page 32: C ++  Programming Languages

32

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

• data types– void, char, short, int, long, float and double

– bool, wchar_t, long long and long double

– char16_t and char32_t

– size_t (typedef long unsigned int size_t)

Page 33: C ++  Programming Languages

33

Extensions to C• Bool

bool bValue; // true (!=0) or false (0)

bool bValue1 = true; // explicit assignmentbool bValue2(false); // implicit assignmentbool bValue1 = !true; // bValue1 will have the value falsebool bValue2(!false); // bValue2 will have the value true

bool bValue = true; // bool bValue = 30; cout << bValue << endl; // 1cout << !bValue << std::endl; // 0 if (!bValue) cout << "The if statement was true" << endl;else cout << "The if statement was false" << endl;

Page 34: C ++  Programming Languages

34

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

Page 35: C ++  Programming Languages

35

Namespaces• Defining namespaces

// in file1.cpp namespace CppNS { double cos(double argInDegrees) { ... } }

// in file2.cpp namespace CppNS { double sin(double argInDegrees) { ... } }

// same as file3.ccp namespace CppNS { double cos(double argInDegrees) { ... } double sin(double argInDegrees) { ... } }

Page 36: C ++  Programming Languages

36

Namespaces• Referring to namespaces

#include <file3>#include <iostream>#include <cmath>using namespace std;

int main(){ cout << "The cosine of 60 degrees is: " << CppNS::cos(60) << ::cos(60); // call the standard std::cos(60) function}

// same as file3.ccpnamespace CppNS{ double cos(double argInDegrees) { … } double sin(double argInDegrees) { … }}

Page 37: C ++  Programming Languages

37

Namespaces• Referring to namespaces

#include <file3>#include <iostream>#include <cmath>

using namespace std;

int main(){ using CppNS::cos; /* ... */ cout << cos(60) // calls CppNS::cos() << ::cos(60); // call the standard std::cos(60) function}

// same as file3.ccpnamespace CppNS{ double cos(double argInDegrees) { … } double sin(double argInDegrees) { … }}

Page 38: C ++  Programming Languages

38

Namespaces• The standard namespace

– The std namespace is reserved by C++

– The standard defines many entities that are part of the runtime available software • e.g., cout, cin, cerr

• the templates defined in the Standard Template Library

• the Generic Algorithms

Page 39: C ++  Programming Languages

39

Namespaces• Nesting namespaces

#include <file3>

int main(){ CppNS::value = 0; CppNS::Virtual::pointer = 0;}

// same as file3.ccpnamespace CppNS{ int value; namespace Virtual { void *pointer; }}#include <file3>

using namespace CppNS;int main(){ value = 0; Virtual::pointer = 0;}

Page 40: C ++  Programming Languages

40

Namespaces• Nesting namespaces

#include <file3>using namespace CppNS; using namespace Virtual;int main(){ value = 0; pointer = 0;}

// same as file3.ccpnamespace CppNS{ int value; namespace Virtual { void *pointer; }}#include <file3>

using namespace CppNS ::Virtual;int main(){

CppNS ::value = 0; pointer = 0;}

Page 41: C ++  Programming Languages

41

Namespaces• Namespace aliasing

#include <file3>namespace CV = CppNS::Virtual;int main(){

CV::pointer = 0;}

// same as file3.ccpnamespace CppNS{ int value; namespace Virtual { void *pointer; }}#include <file3>

namespace CV = CppNS::Virtual; using namespace CV;int main(){

pointer = 0;}

Page 42: C ++  Programming Languages

42

Namespaces• Defining entities outside of their namespaces

#include <file3>namespace CppNS{ namespace Virtual { void *pointer; typedef int INT8[8]; INT8 *squares(); }}// out side the namespace such as in cpp fileCppNS::Virtual::INT8 * CppNS ::Virtual::squares(){ /* … */}

namespace CppNS{ namespace Virtual { void *pointer; typedef int INT8[8];

INT8 *squares() { /* … */ } }}

Page 43: C ++  Programming Languages

43

String• std::string

#include <iostream>#include <string>using namespace std;int main(){

string sString;sString = string("One");cout << sString << endl; // Oneconst string sTwo("Two");sString.assign(sTwo);cout << sString << endl; // TwosString = "Three"; // Assign a C-style stringcout << sString << endl; // ThreesString.assign("Four");cout << sString << endl; // FoursString = '5'; // Assign a charcout << sString << endl; // 5string sOther; // Chain assignmentsString = sOther = "Six";cout << sString << " " << sOther << endl; // Six Six

}

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); /* … */}

Page 44: C ++  Programming Languages

44

String• std::string assignment and swapping

const string sSource("abcdefg");string sDest;sDest.assign(sSource, 2, 4); cout << sDest << endl; // cdefsDest.assign("abcdefg", 4);cout << sDest << endl; // abcdsDest.assign(4, 'g');cout << sDest << endl; // gggg

string sStr1("red");string sStr2("blue);cout << sStr1 << " " << sStr2 << endl; // red blueswap(sStr1, sStr2);cout << sStr1 << " " << sStr2 << endl; // blue red sStr1.swap(sStr2);cout << sStr1 << " " << sStr2 << endl; // red blue

Page 45: C ++  Programming Languages

45

String• std::string inserting

#include <iostream>#include <string>using namespace std;int main(){ string sString("aaaa"); cout << sString << endl; // aaaa sString.insert(2, string("bbbb")); cout << sString << endl; // aabbbbaa sString.insert(4, "cccc"); cout << sString << endl; // aabbccccbbaa const string sInsert("01234567"); // insert substring of sInsert from index [3,7) into sString at index 2 sString.insert(2, sInsert, 3, 4); // aa3456bbccccbbaa cout << sString << endl;}

Page 46: C ++  Programming Languages

46

String• std::string appending

string sString("one");sString += string(" two"); // sString += " two";string sThree(" three");sString.append(sThree);cout << sString << endl; // one two three

string sString("one ");const string sTemp("twothreefour");// append substring of sTemp starting at index 3 of length 5sString.append(sTemp, 3, 5); cout << sString << endl; // one three

Page 47: C ++  Programming Languages

47

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

at access specified character with bounds checking clear clears the contents insert inserts characters erase removes characters compare compares two strings replace replaces specified portion of a string substr returns a substring copy copies characters find find characters in the string rfind find the last occurrence of a substring find_first_of find first occurrence of characters find_last_of find last occurrence of characters /* … */

Page 48: C ++  Programming Languages

48

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 s = "abc"; s.at(2) = 'x'; // ok std::cout << s << '\n'; std::cout << "string size = " << s.size() << '\n'; std::cout << "string capacity = " << s.capacity() << '\n'; try { // throw, even if capacity allowed to access element s.at(3) = 'x'; } catch (std::out_of_range& exc) { std::cout << exc.what() << '\n‘; }}

abxstring size = 3string capacity = 7basic_string::at

Page 49: C ++  Programming Languages

49

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

stoi Convert string to integerstol Convert string to long intstoul Convert string to unsigned integerstoll Convert string to long longstoull Convert string to unsigned long longstof Convert string to float stod Convert string to doublestold 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::cout << str_bin << ": " << i_bin; // -10010110001: -1201

Page 50: C ++  Programming Languages

50

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; // print text to the monitor int nAge; cin >> nAge; // get input from the user if (nAge <= 0) { // print an error message cerr << "Oops, you entered an invalid age!" << endl; return 1; } cout << "You entered " << nAge << " years old" << endl; return 0;}

Page 51: C ++  Programming Languages

51

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;/* Any remaining characters will be left in the stream until the next extraction */

Page 52: C ++  Programming Languages

52

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: HellomynameisOmid

while (cin.get(ch)) input : Hello my name is Omid cout << ch; output : Hello my name is Omid

Page 53: C ++  Programming Languages

53

IOStreams• extraction operator (>>)

char strBuf[11];// only read the first 10 characterscin.get(strBuf, 11); input : Hello my name is Omidcout << strBuf << 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 strBuf[11];cin.get(strBuf, 11); input : Hello! cout << strBuf << endl; output : Hello

cin.get(strBuf, 11);cout << strBuf << endl;/* Consequently, getline() like get() but reads the newline as well */

Page 54: C ++  Programming Languages

54

IOStreams• extraction operator (>>)

/* If you need to know how many character were extracted by the last call of getline(), use gcount() */

char strBuf[100];cin.getline(strBuf, 100);cout << strBuf << endl;cout << cin.gcount() << " characters were read" << endl;

// A special version of getline() for std::stringstring strBuf;getline(cin, strBuf);cout << strBuf << endl;

Page 55: C ++  Programming Languages

55

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 flagcout << 27 << endl; // output : +27cout.unsetf(ios::showpos); // turn off the ios::showpos flagcout << 28 << endl; // output : 28cout.setf(ios::showpos | ios::uppercase);

// basefield : “oct”, “dec”, and “hex”cout.unsetf(ios::dec); // turn off decimal outputcout.setf(ios::hex); // turn on hexadecimal outputcout << 27 << endl; // output : 1b

cout << hex << 27 << endl; // print 27 in hex : 1bcout << 28 << endl; // we're still in hex : 1ccout << dec << 29 << endl; // back to decimal: 29

Page 56: C ++  Programming Languages

56

IOStreams• insertion operator (<<)

cout << true << " " << false << endl; // 0 1 cout.setf(ios::boolalpha);cout << true << " " << false << endl; // true false cout << noboolalpha << true << " " << false << endl; // 0 1 cout << boolalpha << true << " " << false << endl; // true false

cout << fixed << endl; // Use decimal notation for valuescout << setprecision(3) << 123.456 << endl; // 123.456cout << setprecision(4) << 123.456 << endl; // 123.4560

Page 57: C ++  Programming Languages

57

IOStreams• insertion operator (<<)

showpos Prefixes positive numbers with a +noshowpos Doesn’t prefix positive numbers with a +fixed Use decimal notation for valuesscientific Use scientific notation for valuesshowpoint Show a decimal point and trailing 0 s for floating-point values′noshowpoint Don’t show a decimal point and trailing 0 s for floating-point values′setprecision(int) Sets the precision of floating-point numbers (iomanip.h)precision() Returns the current precision of floating-point numbersprecision(int) Sets the precision of floating-point numbers and returns old precisioninternal Left-justifies the sign of the number, and right-justifies the valueleft Left-justifies the sign and valueright Right-justifies the sign and valuesetfill(char) Sets the parameter as the fill character (iomanip.h)setw(int) Sets the field width for input and output to the parameter (iomanip.h)fill() Returns the current fill characterfill(char) Sets the fill character and returns the old fill characterwidth() Returns the current field widthwidth(int) Sets the current field width and returns old field width

Page 58: C ++  Programming Languages

58

IOStreams• insertion operator (<<)

cout << -12345 << endl; // print default value with no field widthcout << setw(10) << -12345 << endl; // print default with field widthcout << setw(10) << left << -12345 << endl; // print left justifiedcout << setw(10) << right << -12345 << endl; // print right justifiedcout << setw(10) << internal << -12345 << endl; // print internally justified

cout.fill('*');cout << -12345 << endl; cout << setw(10) << -12345 << endl; cout << setw(10) << left << -12345 << endl; cout << setw(10) << right << -12345 << endl; cout << setw(10) << internal << -12345 << endl;

-12345 -12345-12345 -12345- 12345-12345****-12345-12345********-12345-****12345

Page 59: C ++  Programming Languages

59

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>stringstream os;os << "en garde!" << endl; // set the stringstream buffer to "en garde!“os.str("en garde!"); // set the stringstream buffer to "en garde!“cout << os.str();os.str(""); os.str(std::string()); os.clear(); // erase the bufferos << "12345 67.89"; // insert a string of numbers into the streamstring strValue;os >> strValue;string strValue2;os >> strValue2;cout << strValue << " - " << strValue2 << endl; // 12345 - 67.89

int nValue;double dValue; os >> nValue >> dValue;

Page 60: C ++  Programming Languages

60

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

operation fails, further operations on the stream are suspended. It 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::goodbitEverything is okay (none of the other three condition flags)

ios::badbitSome kind of fatal error occurred (eg. the program tried read past the end of a file)

ios::eofbitThe stream has reached the end of a file

ios::failbitA non-fatal error occurred (eg. the user entered letters when the program was expecting an integer)

Page 61: C ++  Programming Languages

61

IOStreams• Stream states - Member function

good() Returns true if the goodbit is setbad() Returns true if the badbit is seteof() Returns true if the eofbit is setfail() Returns true if the failbit is setclear() Clears all flags and restores the stream to the goodbitclear(state) Clears all flags and sets the state flag passed inrdstate() Returns the currently set flagssetstate(state) Sets the state flag passed in

Page 62: C ++  Programming Languages

62

IOStreams• Stream states - Member function

void state() { cout << cin.bad() << cin.fail() << cin.eof() << cin.good() << '\n';}int main() { string line; int x; cin >> x; // omid state(); // 0100 cin.clear(); cin >> line; // omid state(); // 0001 getline(cin, line); // state(); // 0001}

/* Whenever an operation fails, further operations on the stream are suspended */

// cin.clear(); cin >> line; // suspended state(); // 0100 getline(cin, line); // suspended state(); // 0100

Page 63: C ++  Programming Languages

63

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())

Page 64: C ++  Programming Languages

64

IOStreams• Input validation

Function Return value----------------------------------------------------------------------------------------------------------------isalnum(int) non-zero if the input is a letter or a digitisalpha(int) non-zero if the input is a letteriscntrl(int) non-zero if the input is a control characterisdigit(int) non-zero if the input is a digitisgraph(int) non-zero if the input is printable character that is not whitespaceisprint(int) non-zero if the input is printable character (including whitespace)ispunct(int) non-zero if the input is neither alphanumeric nor whitespaceisspace(int) non-zero if the input is whitespaceisxdigit(int) non-zero if the input is a hexadecimal digit (0-9, a-f, A-F)

Page 65: C ++  Programming Languages

65

IOStreams• Input validation

cout << "Enter your age: ";string strAge;cin >> strAge;

// Check to make sure each character is a digitfor (unsigned int nIndex=0; nIndex < strAge.length(); nIndex++) if (!isdigit(strAge[nIndex])) { …. }

Page 66: C ++  Programming Languages

66

Your practice: run it int nAge; string str; while (1) { cout << "Enter your age: "; cin >> nAge; // user enter the following : 23dncdlklkd 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 (nAge <= 0) // make sure nAge is positive continue; cin >> str; break; }

Page 67: C ++  Programming Languages

67

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

– ofstream (derived from ostream)• output file

– fstream (derived from iostream). • input/output file

– fstream.h

Page 68: C ++  Programming Languages

68

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 << "This is line 2" << endl;

Page 69: C ++  Programming Languages

69

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 strInput; inf >> strInput; getline(inf, strInput); cout << strInput << endl; }c

Page 70: C ++  Programming Languages

70

IOStreams• fstream : input/output file app Opens the file in append mode

only be used in streams open for output-only operationsate Seeks to the end of the file before reading/writingbinary Opens the file in binary mode (instead of text mode)in Opens the file in read mode (default for ifstream)nocreate Opens the file only if it already existsnoreplace Opens the file only if it does not already existout Opens the file in write mode (default for ofstream)trunc Erases the file if it already exists

// Note we have to specify both in and out because we're using fstreamfstream iofile("Sample.dat", ios::in | ios::out);ofstream myfile; myfile.open ("example.bin", ios::out | ios::app | ios::binary);

Page 71: C ++  Programming Languages

71

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";

Page 72: C ++  Programming Languages

72

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();

Page 73: C ++  Programming Languages

73

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

Page 74: C ++  Programming Languages

74

IOStreams• get and put stream pointers

beg The offset is relative to the beginning of the file (default)cur The offset is relative to the current location of the file pointerend The offset is relative to the end of the file

ifstream inf("Sample.dat");inf.seekg(14, ios::cur); // move forward 14 bytesinf.seekg(-18, ios::cur); // move backwards 18 bytesinf.seekg(22, ios::beg); // move to 22nd byte in fileinf.seekg(24); // move to 24th byte in file// move to the 28th byte before end of the fileinf.seekg(-28, ios::end);

Page 75: C ++  Programming Languages

75

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";

Page 76: C ++  Programming Languages

76

Dynamic memory allocation• new and delete

int nSize = 12;int *pnArray = new int[nSize]; pnArray[4] = 7;delete[] pnArray;/////////////////////////////void doSomething(){ int *pnValue = new int; // Memory leaks}/////////////////////////////int *pnValue = new int; // dynamically allocate an integerdelete pnValue; // pnValue not set to 0 if (pnValue) *pnValue = 5; // will cause a crash

Page 77: C ++  Programming Languages

77

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()) { 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;}

Page 78: C ++  Programming Languages

78

Handling errors• assert statement

int g_anArray[10]; // a global array of 10 charactersint GetArrayValue(int nIndex){ // use if statement to detect violated assumption if (nIndex < 0 || nIndex > 9) return -1; // return error code to caller return g_anArray[nIndex];}int main(){ GetArrayValue(10); return 0;}

Page 79: C ++  Programming Languages

79

Handling errors• assert statement

#include <cassert> // for assert()using namespace std;int g_anArray[10]; // a global array of 10 charactersint GetArrayValue(int nIndex){ // we're asserting that nIndex is between 0 and 9 assert(nIndex >= 0 && nIndex <= 9); // this is line 7 in Test.cpp return g_anArray[nIndex];}int main(){ GetArrayValue(10); // error in line 7 … return 0;}

Page 80: C ++  Programming Languages

80

Inline functions

int min(int nX, int nY){ return nX > nY ? nY : nX;} int main(){ using namespace std; cout << min(5, 6) << endl; cout << min(3, 2) << endl; return 0;}

Page 81: C ++  Programming Languages

81

Inline functionsinline int min(int nX, int nY){ return nX > nY ? nY : nX;}/* 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; cout << (3 > 2 ? 2 : 3) << endl; return 0;}

Page 82: C ++  Programming Languages

82

Function templates

int maxF(int nX, int nY){ return (nX > nY) ? nX : nY;}double maxF(double dX, double dY){ return (dX > dY) ? dX : dY;}// …

Page 83: C ++  Programming Languages

83

Function templates

// this is the template parameter declarationtemplate <typename Type>Type maxF(Type dX, Type dY){ return (dX > dY) ? dX : dY;}// …int nValue = maxF(3, 7); // returns 7double dValue = maxF(6.34, 18.523); // returns 18.523char chValue = maxF('a', '6'); // returns 'a‘ int n2 = maxF<int>(3, 7); // returns 7 double d2 = maxF<int>(6.34, 18.523); // returns 18

Page 84: C ++  Programming Languages

84

Function templatestemplate<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)}

Page 85: C ++  Programming Languages

85

Function templates

// this is the template parameter declarationtemplate <typename T, typename U>T max(T dX, U dY){ return (dX > dY) ? dX : dY;}// …int nValue = max(3, 7); // returns 7double dValue = max(6.34, 18.523); // returns 18.523char chValue = max('a', '6'); // returns 'a'

Page 86: C ++  Programming Languages

86

Function templates

// return type depends on template parameterstemplate <typename T, typename U>auto add(T t, U u) -> decltype(t + u){

// …return t + u;

}

Page 87: C ++  Programming Languages

87

Reference

• http://en.cppreference.com/w/

• http://www.cplusplus.com/reference/