410 likes | 509 Views
C++ Overview Input/Output New Data Types Expressions Declarations, Operators Control Structures. C++. 159.234. Bjarne Stroustrup. of AT&T Bell Laboratories. Designed and implemented a new language in the early 1980’s.
E N D
C++ Overview Input/Output New Data Types Expressions Declarations, Operators Control Structures 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” 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). C++
159.234 A word from the inventor C++ "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
Object Oriented Programming (OOP) language? • A programming language in which programmers define an abstract data type consisting of both: • dataand • the operations (functions) that can be applied to data.
159.234 AIMS C++ Make programming more enjoyable. Be a general purpose language that: is a better C supports data abstraction supports object-oriented programming supports generic programming
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). 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. C++
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 } */ Comments
159.234 COMMENTS 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
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 iis 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 << Input and Output
C++ streams A stream is a sequence of bytes moving to/from a device or file.
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. cin 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);
159.234 To alter the appearance of output, we insert manipulatorsinto the stream, or call functions. Text Formatting #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 left align ios::right 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.
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). C++
159.234 Enumerated types: Use this to create variables that can store days: day d1,d2; d1 = tue; d2 = d1; if (d2 == wed) { ... } #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. C++ Enumerated types allow the compiler to check the values associated with them. d1 = 1; // will produce a warning enum is implemented using integers.
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 (d1) { 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. 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. C++
159.234 Values of expressions: C++ 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));
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. C++
159.234 The conditional operator: A 'ternary' operator - it takes three arguments: expr1 ? expr2 : expr3 If expr1 is true then expr2 is evaluated otherwise expr3 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; C++
159.234 break 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. C++
159.234 continue This is different from a while loop i = 0; while (i<total) { cin >> c; if (c > 'A') { continue; //i is not incremented } i++; } 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 } } 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. 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. 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; } 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. for (int j=0;j<10;j++) { cout << j << k; // is an error! int k = j; cout << k; } C++
C++ streams A stream is a sequence of bytes moving to/from a device or file.
Input from Keyboard Store inithe value entered from the keyboard: cin >> i; By defaultcin skips all white spaces (blank, tab, newline). Get a complete line of text (the newline character is read & discarded): cin.getline(s, maxNoOfChars); s must be a string and maxNoOfCharsan integer (getline is a method of the cin object, set up for us by the system )
Reading From File C-way #include <stdio.h> FILE *f; f = fopen(“data.txt”, “r”); fscanf(f,"%d %d",&n1,&n2); fclose(f); C++ way #include <fstream.h> ifstream inFile; inFile.open(“data.txt”); inFile >> n1 >> n2; inFile.close(();
Sending Data To File #include <stdio.h> FILE *f; f = fopen(“result.txt”, “w”); ••• fprintf(f,"%d %d",n1,n2); fclose(f); C-way C++ way #include <fstream.h> ••• ofstream outFile; outFile.open(“result.txt”); outFile << n1 << n2; outFile.close();
File Name Selected By User char* fileName; .. . cout << "Enter file name: "; cin >> fileName; ifstream inFile; inFile.open(fileName); if( !inFile){ cerr <<"No file-error here!"; exit(EXIT_FAILURE);//include <stdlib.h> } inFile.close(); cout <<"Done"; .. .
Attention! 1. Check for the existence of the file. if(!myFile){//no file to work with cerr <<“Failed to find/create file<<endl; return 1; //notify the system something was wrong } This (common) trick works because myFile 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:\mystuff\input.txt” We must use: ifstream myFile(“A:\\mystuff\\input.txt”);
Attention! 2. Mixing numbers and strings when working with files needs careful consideration. while(inFile >> num1 >> num2 >> ch >> word) 23.4 56 M Demlow 12 4 A Smith Is OK for this inFile: 23.4 56 M Ann Demlow 12 4 A Smith But it does not work for
#include <iostream> #include <fstream> using namespace std; int main(){ cout << “Hi there!" << endl; inti; while( cin >> i ){ cout << i << endl; } return 0; } Output is: Hi there! 1 1 2 2 Terminated with ^D or ^Z
#include <iostream> #include <fstream> using namespace std; int main(){ ifstream myInputStream( "testinput.txt" ); if( !myInputStream ){ cerr << "error opening input file" << endl; exit(1); } ofstream myOutputStream( "testoutput.txt" ); if( !myOutputStream ){ cerr << "error opening output file" << endl; exit(1); } while( myInputStream >> i ){ myOutputStream << i * 10 << endl; } myInputStream.close(); myOutputStream.close(); return 0; } Input of: 1 2 3 4 5 6 7 8 9 0 Gives output file: 10 20 30 40 50 60 70 80 90 0
memory ---- ----- ---- ifstream var Disk file >>… cin Keyboard Monitor cout cerr <<… ---- ----- ---- ofstream var Disk file Summary
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 x1, y1, x2 ,y2 Use dynamic memory allocation for the array
Exercise Use the following format for the output file. wBound.x1 = v1, wBound.y1 = v2, wBound.x2 = v3, wBound.y2 = v4 Where vi is a value read from the file Sample output file: out.txt wBound.x1 = 1, wBound.y1 = 2.2, wBound.x2 = 3, wBound.y2 = 4.4 wBound.x1 = 5.5, wBound.y1 = 6.6, wBound.x2 = 7, wBound.y2 = 8.8 wBound.x1 = 1.1, wBound.y1 = 2.1, wBound.x2 = 3.1, wBound.y2 = 4.1
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 usecin/cout, we must include<iostream> To useifstream/ofstream, we must include<fstream> • Next: • Formatting output, program structure, types in C++, enum, const. • Textbook p.30-34,37(const), 38, 383, browse p. 414-417