C C Overview InputOutput New Data Types Expressions

  • Slides: 40
Download presentation
C++ • • • C++ Overview Input/Output New Data Types Expressions Declarations, Operators Control

C++ • • • C++ Overview Input/Output New Data Types Expressions Declarations, Operators Control Structures 1

C++ 159. 234 Bjarne Stroustrup of AT&T Bell Laboratories Designed and implemented a new

C++ 159. 234 Bjarne Stroustrup of AT&T Bell Laboratories Designed and implemented a new language in the early 1980’s. Initially called “C with Classes” Classes it became known as C++, an incremental step up from C. It was designed to deliver: the flexibility and efficiency of C with the facilities for program organisation of the Simula language (usually referred to as object-oriented programming). 2

C++ 159. 234 A word from the inventor "C makes it easy to shoot

C++ 159. 234 A word from the inventor "C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do, it blows away your whole leg. " - Bjarne Stroustrup http: //www. research. att. com/~bs/C++. html 3

Object Oriented Programming (OOP) language? A programming language in which programmers define an abstract

Object Oriented Programming (OOP) language? A programming language in which programmers define an abstract data type consisting of both: • data and • the operations (functions) that can be applied to data. 4

C++ 159. 234 AIMS Make programming more enjoyable. Be a general purpose language that:

C++ 159. 234 AIMS Make programming more enjoyable. Be a general purpose language that: is a better C supports data abstraction supports object-oriented programming supports generic programming 5

C++ 159. 234 DESIGN PRINCIPLES Don’t get involved in a quest for perfection. Be

C++ 159. 234 DESIGN PRINCIPLES Don’t get involved in a quest for perfection. Be useful immediately. Don’t try to force people. It is more important to allow a useful feature than to prevent every misuse. Leave no room for a lower-level language below C++ (except assembler). 6

C++ 159. 234 Language rules: Provide as good support for user-defined types as for

C++ 159. 234 Language rules: Provide as good support for user-defined types as for built-in types. Locality is good. Preprocessor usage should be eliminated. No gratuitous incompatibilities with C. If you don’t use a feature, you don’t pay for it. 7

Comments 159. 234 COMMENTS C++ allows the use of // as a comment all

Comments 159. 234 COMMENTS C++ allows the use of // as a comment all text to the end of the line is ignored. Use /*. . . */ for large multi-line blocks of comments // for small comments. // allows nesting of comments. Commenting out a large block of code does not work in C, if the block already contains a small comment. /* for (i=0; i<10; i++) { k = i*i; /*k /* is the square of i*/ } */ /* for (i=0; i<10; i++) { k = i*i; // this is ok } */ 8

Comments 159. 234 COMMENTS Sometimes its useful to use a pre-processor directive to comment

Comments 159. 234 COMMENTS Sometimes its useful to use a pre-processor directive to comment a large chunk of code: #if 0 commented out code with /* comments */ #endif 9

Input and Output 159. 234 Input and Output: C++ uses a new way to

Input and Output 159. 234 Input and Output: C++ uses a new way to perform console I/O. Its major advantage over printf and getchar, is that it is both consistent and safer. printf("%s", i); /* but i is an integer */ is not detected as an error by most compilers C++ instead uses the notion of streams manipulators overloading it overloads the two operators >> and << 10

C++ streams A stream is a sequence of bytes moving to/from a device or

C++ streams A stream is a sequence of bytes moving to/from a device or file. 11

cin 159. 234 Input and Output #include <iostream>. . . cout << "Hello World“

cin 159. 234 Input and Output #include <iostream>. . . cout << "Hello World“ << endl; writes "Hello World" on the console and then goes to the next line. cout << "i = " << i; //outputs the value of i For input: cin >> i; //The >> point the way the data is going. There is no need to use pointers! To get a complete line of text (the newline is read and discarded) cin. getline(s, max_no_of_chars); 12

Text Formatting 159. 234 To alter the appearance of output, we insert manipulators into

Text Formatting 159. 234 To alter the appearance of output, we insert manipulators into the stream, or call functions. #include <iostream> endl outputs a new line dec uses decimal values hex uses hexadecimal values width(int w) field width of next output fill(char c) fill character setf(flag) set special flags ios: : left align ios: : right align cout. fill('0'); cout. setf(ios: : right); cout << hours << ": "; cout. width(2); cout << minutes << ". "; cout. width(2); cout << seconds << endl; sprintf is still used to format a string before displaying it. 13

C++ 159. 234 NEW SIMPLE TYPES C++ defines two new simple types: bool Boolean

C++ 159. 234 NEW SIMPLE TYPES C++ defines two new simple types: bool Boolean variables can represent either true or false. bool test; test = true; test = (x<5); bool, true and false are new keywords in C++ and cannot be used as identifiers. On output the values are shown as 0 (false) and 1 (true). wchar_t is a 'wide' character type is designed to allow alphabets with many characters (e. g. Japanese characters). 14

C++ Enumerated types: #define is used to link names to constants. Use of the

C++ Enumerated types: #define is used to link names to constants. Use of the pre-processor is frowned on in C++. Enumerated types are one way of replacing it. enum day {sun, mon, tue, wed, thu, fri, sat}; defines a new type day. 159. 234 Use this to create variables that can store days: day d 1, d 2; d 1 = tue; d 2 = d 1; if (d 2 == wed) {. . . } Enumerated types allow the compiler to check the values associated with them. d 1 = 1; // will produce a warning enum is implemented using integers. 15

C++ 159. 234 Enumerated types: In the above example sun is represented by 0,

C++ 159. 234 Enumerated types: In the above example sun is represented by 0, mon by 1 etc. There is no easy way to print out enumerated types. switch (d 1) { case sun: cout << "Sunday"; break; case mon: . . . } Another way of avoiding the pre-processor is by using const: const int MAX = 4000; MAX is a non-changeable integer variable. You can initialise constants but not assign to them. 16

C++ 159. 234 Values of expressions: We are familiar with the normal arithmetic operators:

C++ 159. 234 Values of expressions: We are familiar with the normal arithmetic operators: + - * / a + b is an expression and its value is the sum of the contents of the two variables. However, in C++, the following statements below: b = 2; c = 3; a = b + c; can also been written as: a = (b=2) + (c=3); DON’T do this. 17

C++ 159. 234 Values of expressions: However consider: a = b = c =

C++ 159. 234 Values of expressions: However consider: a = b = c = 1; This sets several variables to one - and is used. The brackets have been omitted - if we insert them, we get: a = (b = (c = 1)); 18

C++ 159. 234 Comma operator: for (i=0; i<10; i++) { } In most uses

C++ 159. 234 Comma operator: for (i=0; i<10; i++) { } In most uses of a for loop, the initialisation phase and the increment phase only have one expression. To initialise two variables we can use the comma operator for (i=0, j=0; i<10; i++, j++) { } The comma operator can be used anywhere: i = 0, j = 0; //this is OK. Its value is the value of the left-hand expression. k = (i=4), (j=5); k gets the value 4. But DON’T do this. 19

C++ 159. 234 The conditional operator: A 'ternary' 'ternary operator - it takes three

C++ 159. 234 The conditional operator: A 'ternary' 'ternary operator - it takes three arguments: expr 1 ? expr 2 : expr 3 If expr 1 is true then expr 2 is evaluated otherwise expr 3 is evaluated. It allows a shorthand form of an if statement: if (y < z) { x = y; } else { x = z; } can also be written: x = (y < z) ? y : z; 20

C++ 159. 234 break is used in a switch statement to stop execution falling

C++ 159. 234 break is used in a switch statement to stop execution falling through from one case to the next: switch (c) { case 'A': … do something break; case 'B': … etc break; } break can also be used in loops as well. while (true) { if (a == b) { break; }. . . } break ends the inner-most loop that encloses it. 21

C++ 159. 234 continue goes to the beginning of the loop. Inside a for

C++ 159. 234 continue goes to the beginning of the loop. Inside a for loop the 'increment' expression is evaluated after a continue : for (i=0; i<total; i++) { cin >> c; if (c > 'A') { continue; // i is incremented } } This is different from a while loop i = 0; while (i<total) { cin >> c; if (c > 'A') { continue; //i is not incremented } i++; } 22

C++ 159. 234 goto The use of goto is frowned upon! Try not to

C++ 159. 234 goto The use of goto is frowned upon! Try not to use it. It can be helpful in getting out of deeply nested loops, when a break isn't much use. Explicit jumps around pieces of code are used a lot in assembler programming. A label has the same syntax as an identifier, with a colon added at the end for (i=0; i<10; i++) { for (j=0; j<20; j++) {. . . if (a[i][j] == 10) goto found; } }. . . found: cout << "I found it! " << endl; Better: create a function and use return. 23

C++ 159. 234 Declarations: C allows declarations at the start of a { }

C++ 159. 234 Declarations: C allows declarations at the start of a { } block. Variables only exists while the block is being executed. We normally declare variables at the start of a function, but this is also ok: int main () { int i; for (i=0; i<10; i++) { int temp; temp = i; } } temp only exists within the for loop. 24

C++ 159. 234 DECLARATIONS C++ allows declarations anywhere. The variable exists from that point

C++ 159. 234 DECLARATIONS C++ allows declarations anywhere. The variable exists from that point to the end of the enclosing block. for (int j=0; j<10; j++) { cout << j; int k = j; cout << k; } for (int j=0; j<10; j++) { cout << j << k; // is an error! int k = j; cout << k; } j exists while the loop is executing and maybe longer depending on compiler settings. k exists from its declaration to the end of the loop. 25

C++ streams A stream is a sequence of bytes moving to/from a device or

C++ streams A stream is a sequence of bytes moving to/from a device or file. 26

Input from Keyboard Store in i the value entered from the keyboard: cin >>

Input from Keyboard Store in i the value entered from the keyboard: cin >> i; By default cin skips all white spaces (blank, tab, newline). Get a complete line of text (the newline character is read & discarded): cin. getline(s, max. No. Of. Chars); s must be a string and max. No. Of. Chars an integer (getline is a method of the cin object, set up for us by the system ) 27

Reading From File C-way #include <stdio. h> FILE *f; f = fopen(“data. txt”, “r”);

Reading From File C-way #include <stdio. h> FILE *f; f = fopen(“data. txt”, “r”); fscanf(f, "%d %d", &n 1, &n 2); fclose(f); C++ way #include <fstream. h> ifstream in. File; in. File. open(“data. txt”); in. File >> n 1 >> n 2; in. File. close((); 28

Sending Data To File C-way #include <stdio. h> FILE *f; f = fopen(“result. txt”,

Sending Data To File C-way #include <stdio. h> FILE *f; f = fopen(“result. txt”, “w”); • • • fprintf(f, "%d %d", n 1, n 2); fclose(f); C++ way #include <fstream. h> • • • ofstream out. File; out. File. open(“result. txt”); out. File << n 1 << n 2; out. File. close(); 29

File Name Selected By User char* file. Name; . . . cout << "Enter

File Name Selected By User char* file. Name; . . . cout << "Enter file name: "; cin >> file. Name; ifstream in. File; in. File. open(file. Name); if( !in. File){ cerr <<"No file-error here!"; exit(EXIT_FAILURE); //include <stdlib. h> } in. File. close(); cout <<"Done"; . . . 30

Reading data ( assume char ch; char str[60]; ) cin my. File Doing: Need

Reading data ( assume char ch; char str[60]; ) cin my. File Doing: Need #include<iostream> Need #include<fstream> cin >>ch my. File >> ch cin. get(ch) my. File. get(ch) Skip white spaces Reads every char ch cin. get(str, 40, ‘#’) cin. get(str, 40) Read C-strings (leaves termin. ch. in the stream), appends ‘’. cin. getline(str, 60, ’ my. File. getline(str, #’) 60, ’#’) cin. getline(str, 60) my. File. getline(str, 6 0) Read C-strings (removes termin. ch. from stream), appends ‘’. 31

Output data cout #include <iostream> cout <<value my. File #include<fstream> Doing: my. File<<value Write

Output data cout #include <iostream> cout <<value my. File #include<fstream> Doing: my. File<<value Write out value (char, int, C/C++ strings …) cout. put(ch) my. File. put(ch) Write out char ch 32

Attention! 1. Check for the existence of the file. if(!my. File){ //no file to

Attention! 1. Check for the existence of the file. if(!my. File){ //no file to work with !my. File cerr <<“Failed to find/create file<<endl; return 1; //notify the system something was wrong } This (common) trick works because my. File will have a NULL pointer if the file open operation failed. NULL is generally the same as zero so !NULL evaluates true. When the file is in a different directory, e. g “A: mystuffinput. txt” We must use: ifstream my. File(“A: \mystuff \input. txt”); \ \ 33

Attention! 2. Mixing numbers and strings when working with files needs careful consideration. while(in.

Attention! 2. Mixing numbers and strings when working with files needs careful consideration. while(in. File >> num 1 >> num 2 >> ch >> word) Is OK for this in. File: But it does not work for 23. 4 12 4 56 M Demlow A Smith 23. 4 56 M Ann Demlow 12 4 A Smith 34

#include <iostream> #include <fstream> using namespace std; int main(){ cout << “Hi there!" <<

#include <iostream> #include <fstream> using namespace std; int main(){ cout << “Hi there!" << endl; int i; while( cin >> i ){ ) cout << i << endl; } return 0; • Output is: Hi there! 1 1 2 2 Terminated with ^D or ^Z } 35

#include <iostream> #include <fstream> using namespace std; int main(){ ifstream my. Input. Stream( "testinput.

#include <iostream> #include <fstream> using namespace std; int main(){ ifstream my. Input. Stream( "testinput. txt" ); if( !my. Input. Stream ){ cerr << "error opening input file" << endl; exit(1); } ofstream my. Output. Stream( "testoutput. txt" ); if( !my. Output. Stream ){ cerr << "error opening output file" << endl; exit(1); } while( my. Input. Stream >> i ){ my. Output. Stream << i * 10 << endl; } my. Input. Stream. close(); my. Output. Stream. close(); return 0; } • Input of: 123456789 0 • Gives output file: 10 20 30 40 50 60 70 80 90 0 36

Summary Disk file ---- memory ifstream var ---- Keyboard Monitor cin cout cerr ----

Summary Disk file ---- memory ifstream var ---- Keyboard Monitor cin cout cerr ---- >>… <<… ofstream var ---- Disk file 37

Exercise Write a complete program that will read the following data from a text

Exercise Write a complete program that will read the following data from a text file, then generate an output file. Example: Number of items 3 1 2. 2 3 4. 4 5. 5 6. 6 7 8. 8 1. 1 2. 1 3. 1 4. 1 Store these items into an array of struct x 1, y 1, x 2 , y 2 Use dynamic memory allocation for the array 38

Exercise Use the following format for the output file w. Bound. x 1 =

Exercise Use the following format for the output file w. Bound. x 1 = v 1, w. Bound. y 1 = v 2, w. Bound. x 2 = v 3, w. Bound. y 2 = v 4 Where vi is a value read from the file Sample output file: out. txt w. Bound. x 1 = 1, w. Bound. y 1 = 2. 2, w. Bound. x 2 = 3, w. Bound. y 2 = 4. 4 w. Bound. x 1 = 5. 5, w. Bound. y 1 = 6. 6, w. Bound. x 2 = 7, w. Bound. y 2 = 8. 8 w. Bound. x 1 = 1. 1, w. Bound. y 1 = 2. 1, w. Bound. x 2 = 3. 1, w. Bound. y 2 = 4. 1 39

Summary File streams work like streams coming from/going to the keyboard (cin)/ screen (cout),

Summary File streams work like streams coming from/going to the keyboard (cin)/ screen (cout), except that the other end is a file instead of an input/output device. To use cin/cout, we must include <iostream> To use ifstream/ofstream, we must include <fstream> Next: Formatting output, program structure, types in C++, enum, const. Textbook p. 30 -34, 37(const), 383, browse p. 414 -417 40