Post on 01-Jan-2016
description
1
C++• C++ Overview• Input/Output• New Data Types• Expressions• Declarations, Operators• Control Structures
2
C++
Bjarne Stroustrup
159.234
Designed and implemented a new language in the early 1980’s.
Initially called “C with ClassesC with Classes” it became known as C++, an incremental step up from C.
It was designed to deliver:the flexibility and efficiency of C withthe facilities for program organisation of the Simula language (usually referred to as object-oriented programming).
of AT&T Bell Laboratories
3
C++
A word from the inventor
159.234
"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
4
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.
5
C++
AIMS
159.234
Make programming more enjoyable.
Be a general purpose language that:is a better Csupports data abstractionsupports object-oriented programmingsupports generic programming
6
C++
DESIGN PRINCIPLES
159.234
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).
7
C++
Language rules:
159.234
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.
8
Comments
COMMENTS
159.234
C++ allows the use of //// as a commentall 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 }*/*/
9
Comments
COMMENTS
159.234
Sometimes its useful to use a pre-processor directive to comment a large chunk of code:
#if 0#if 0 commented out code with /*/* comments */*/#endif#endif
10
Input and Output
Input and Output:
159.234
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("%printf("%ss",i); /* but i is an ",i); /* but i is an integerinteger */ */ is not detected as an error by most compilersis not detected as an error by most compilers.
C++ instead uses the notion ofstreamsmanipulatorsoverloading
it overloads the two operators >> operators >> and <<<<
11
C++ streamsC++ streams
A stream is a sequence of bytes moving to/from a device or file.
12
cin
Input and Output
159.234
#include <iostream>#include <iostream>...
cout << "Hello World“ << endl;cout << "Hello World“ << endl;
writes "Hello World" on the console and then goes to the next line.
cout << "i = " << i; cout << "i = " << i; //outputs the value of i
For input: cin >> i;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);cin.getline(s, max_no_of_chars);
13
Text FormattingTo alter the appearance of output, we insert manipulatorsmanipulators into the stream, or call functions.
159.234
#include <iostream>
endl outputs a new linedec uses decimal valueshex uses hexadecimal values
width(int w) field width of next output
fill(char c) fill charactersetf(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;
sprintfsprintf is still used to format a string before displaying it.
14
C++
NEW SIMPLE TYPES
159.234
C++ defines two new simple types: boolBoolean variables can represent either true or false. bool test; test = true; test = (x<5);
bool, true and falseare 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).
15
C++Enumerated types:
159.234
#define#define is used to link names to constants.
Use of the pre-processor is frowned on in C++.
Enumerated typesEnumerated types are one way of replacing it.
enum day enum day {{sun,mon,tue,wed,thu,fri,sat};};
defines a new type day.
Enumerated types allow the compiler to check the values associated with them.
d1 = 1; // will produce a warning// will produce a warning
enum is implemented using integers.
Use this to create variables that can store days: dayday d1,d2; d1 = tue; d2 = d1; if (d2 == wed) { ... }
16
C++
Enumerated types:
159.234
In the above example sunsun is represented by 00, mon by 1 etc.There is no easy way to print out enumerated types. switch (d1) {switch (d1) {
case case sunsun::cout << "Sunday";cout << "Sunday";break;break;
case case monmon::......}}
Another way of avoiding the pre-processor is by using const: const int MAX = 4000;const int MAX = 4000;
MAX is a non-changeable integer variable.You can initialise constants but notnot assign to them.
17
C++
Values of expressions:
159.234
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 thisDON’T do this..
18
C++
Values of expressions:
159.234
However consider:
a = b = c = 1;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));a = (b = (c = 1));
19
C++
Comma operator:Comma operator:
159.234
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.But DON’T do this.
20
C++
The conditional operator:
159.234
A 'ternary'ternary' operator - it takes three arguments: expr1 ? expr2 : expr3expr1 ? expr2 : expr3
If expr1 is true then expr2 is evaluatedotherwise expr3 is evaluated.It allows a shorthand form of an if statement: if (y < z) { x = yy; } else { x = zz; }can also be written: x = (y < z) ? y : z;
21
C++
break
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;break; case 'B': … etc break;break; }
break can also be used in loops as well.
while (true) { if (a == b) {
break;break;}
... }
break ends the inner-most loop that encloses it.
22
C++
continue
159.234
continuecontinue goes to the beginning of the loop.
Inside a for loop the 'increment' expression is evaluatedis evaluated after a continue :
for (i=0; i<total; i++) { cin >> c; if (c > 'A') { continue;continue; // i is incremented } }
This is different from a while loop
i = 0; while (i<total) { cin >> c; if (c > 'A') { continue;continue; //i is not incrementedi is not incremented } i++; }
23
C++
goto
159.234
The use of goto is frowned upon! Try not to use it.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;goto found; } } ...found:found: cout << "I found it! " << endl;
Better: create a function and use return.
24
C++
Declarations:
159.234
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;int temp; temp = i; } }
temp only exists within the for loop.temp only exists within the for loop.
25
C++DECLARATIONS
159.234
C++ allows declarations anywhere.
The variable exists from that point to the end of the enclosing block.
for (int j=0int j=0;;j<10;j++) { cout << j; int int kk = j; = j; cout << kk; }
j exists while the loop is executing and maybe longer depending on compiler settings.
kk exists from its declarationfrom its declaration to the end of the loop.
for (int j=0;j<10;j++) { cout << j << kk; // is an error!is an error! int k = j;int k = j; cout << k; }
26
C++ streamsC++ streams
A stream is a sequence of bytes moving to/from a device or file.
27
Input from KeyboardInput from Keyboard
Store in i the value entered from the keyboard:
cin >> i;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, maxNoOfChars);cin.getline(s, maxNoOfChars);
s must be a string and maxNoOfChars an integer(getline is a method of the cin object, set up for us by the system )
28
Reading From FileReading From File
#include <fstream.h>ifstream inFile;inFile.open(“data.txt”);inFile >> n1 >> n2;inFile.close(();
#include <stdio.h>
FILE *f;
f = fopen(“data.txt”, “r”);
fscanf(f,"%d %d",&n1,&n2);
fclose(f);
C-way
C++ way
29
Sending Data To FileSending Data To File
#include <fstream.h>
•••ofstream outFile;outFile.open(“result.txt”);outFile << n1 << n2;outFile.close();
#include <stdio.h>
FILE *f;
f = fopen(“result.txt”, “w”);
•••
fprintf(f,"%d %d",n1,n2);
fclose(f);
C-wayC-way
C++ C++ wayway
30
File Name Selected By UserFile 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";.. .
31
Reading data ( assume char ch; char str[60]; )
cin
Need #include<iostream>
myFile Need #include<fstream>
Doing:
cin >>ch myFile >> ch Skip white spaces
cin.get(ch) myFile.get(ch) Reads every char ch
cin.get(str,40,‘#’)
cin.get(str,40)Read C-strings (leaves termin. ch. in the stream), appends ‘\0’.
cin.getline(str,60,’#’)
cin.getline(str,60)
myFile.getline(str, 60,’#’)
myFile.getline(str,60)
Read C-strings (removes termin. ch. from stream), appends ‘\0’.
32
Output data
cout
#include <iostream>
myFile #include<fstream>
Doing:
cout <<value myFile<<value Write out value (char, int, C/C++ strings …)
cout.put(ch) myFile.put(ch) Write out char ch
33
Attention!1. Check for the existence of the file.
if(!myFile!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 pointerNULL 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”);
34
Attention!2. Mixing numbers and strings when working with files needs careful consideration.
while(inFile >> num1 >> num2 >> ch >> word)while(inFile >> num1 >> num2 >> ch >> word)
Is OK for this inFile:23.4 56 M Demlow
12 4 A Smith
But it does not work for 23.4 56 M Ann Demlow
12 4 A Smith
35
#include <iostream>#include <fstream>
using namespace std;
int main(){
cout << “Hi there!" << endl; int i; while( cin >> i )while( cin >> i ){ cout << i << endl; } return 0;}
• Output is:Hi there!1122
Terminated with ^D or ^Z
36
#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:1020304050607080900
37
SummarySummary memory
Keyboard
Monitor
cin
cout
cerr
>>…
<<…
----
-----
----
Disk file ifstream var
Disk file
----
-----
----
ofstream var
38
ExerciseExercise
Write a complete program that will read the following data from a text file, then generate an output file.
31 2.2 3 4.45.5 6.6 7 8.81.1 2.1 3.1 4.1
Store these items into an array of struct
Use dynamic memory allocation for the array
Example: Number of items
x1, y1, x2 ,y2
39
ExerciseExercise
wBound.x1 = 1, wBound.y1 = 2.2, wBound.x2 = 3, wBound.y2 = 4.4wBound.x1 = 5.5, wBound.y1 = 6.6, wBound.x2 = 7, wBound.y2 = 8.8wBound.x1 = 1.1, wBound.y1 = 2.1, wBound.x2 = 3.1, wBound.y2 = 4.1
Use the following format for the output fileoutput file.
wBound.x1 = v1, wBound.y1 = v2, wBound.x2 = v3, wBound.y2 = v4
Where vivi is a value read from the file
Sample output file: out.txt
40
SummarySummary
Next: Formatting output, program structure, types in C++, enum, const. Textbook p.30-34,37(const), 38, 383, browse p. 414-417
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 <<ioiostream>stream>To use ifstream/ofstream, we must include <fstream><fstream>