c++ vs. java who will win?. look ma, no classes! c++ was conceived as an object-oriented extension...

56
C++ Vs. Java Who will win?

Upload: felicity-parrish

Post on 26-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

C++ Vs. Java

Who will win?

Look Ma, no classes!

• C++ was conceived as an object-oriented extension to C

• C was (is) purely procedural language– FunctionsFunctions (methods) separate from data

– Complex data structures exist that are not objects

• Entire programs can be written using only non-non-membermember functions, or (almost) only classes, or (most commonly) some mixture

Structure of a C++ program

• Basic unit is function, not class• Most programs made up of multiple

functions• A main function is required in order for a

source code file to be a program– One main function must exist– No more than one can exist in the same

program

C++: Java without the “training wheels”

• C++ isn’t strongly typed– Can do assignment (including demotion)

without cast (but not without consequence)– Example:

double d = 3.9999;

int x = d;

// x is assigned 3 – value is truncated, not rounded

C++ isn’t strongly typed

• Among the simple types, just about any data can be assigned to any variable– Value assigned is automatically converted to “equivalent”

value of variable type– May lose precision– This is called implicit type coercionimplicit type coercion– Can still do explicit type castingexplicit type casting, as we do with Java

• Boolean values (true and false) are represented as int values– 0 is false– AnyAny other value is true

C++ lacks training wheels

• No bounds checking on arrays– Can overwrite memory that isn’t allocated to

your array– Basis of lots of viruses

• C++ is powerful and potentially dangerous – like making paper dolls with a chainsaw

C++ code libraries

• C++ has a rich library of functions, similar to Java’s library of classes and objects– Includes libraries inherited from C

– Libraries specific to C++ usually contain classes, objects

• Access to libraries via preprocessor directivepreprocessor directive #include

• The #include directive is tied to a header fileheader file and an object fileobject file

Java data types and their C++ counterparts

• Javabyte (signed, 8 bits)short (signed, 16 bits)int (signed, 32 bits)long (signed, 64 bits)boolean (true/false)char (16 bits, Unicode)float (32 bits)double (64 bits)voidString

• C++char (sort of)int, shortlong, intlongboolchar (sort of - 8 bit ASCII)floatdoublevoidstring

Note: string type is not primitive, built-in type in either language

Notes on C++ data types

• Language specification doesn’t specify actual sizes, only relative sizes, as follows:– short <= int <= long

– float <=double

• Typically, char is 8-bit; uses ASCII, not Unicode• Numbers can be designated “unsigned”

– all positive

– doubles magnitude of maximum value

Simple C++ program example

#include <iostream>using namespace std;

int main () {unsigned int x;cout << “Enter a number: ”;cin >> x;cout << “You entered ” << x << endl;system(“PAUSE”); // compiler-specificreturn 0;

}

Notes on example

• Entire program contained in main function – no enclosing class

• Function heading for main:– Return type is typically int, not void– No other modifiers (e.g. public, static)– No parameters (this may vary)

• Return statement required– Function main has return type of int– 0 is traditional return value – signal to operating system

(UNIX) that program ended normally

Preprocessor directives

• The first line of code in the example program: #include <iostream>– isn’t, technically, a C++ instruction; it is a preprocessor

directive

– The closest analog in Java is an import statement

• You can use as many or as few of these as you need, in any order.

• They should appear at the beginning of the file, before any C++ statements

Input/Output in C++

• Streaming I/O; a standard library (iostream) provides objects similar to Java’s System.out and System.in

• 2 output stream objects defined in iostream library:– cout: standard output stream (screen)– cerr: also screen by default

• 1 input stream object: cin, represents standard input (keyboard)

Input/output in C++

• I/O operations are performed by operatorsoperators (not methods or functions, per se)– Insertion operatorInsertion operator (<<) does output

– Extraction operatorExtraction operator (>>) does input

• Direction of “arrows” indicates data destination:– << inserts data on to output stream (cout)

– >> extracts data from input stream (cin) into a variable

Console output

• The object cout (from iostream) represents the standard output stream (screen)

• The insertion operator is used to insert expressions onto the screen– Can be as few as one or as many as ??? expressions

– Each separate expression gets its own insertion operator

– Values of expressions appear on screen in the order of appearance in source code, from left to right

<< is a binary operator<< is called the output or insertion operator

<< is left associative

EXPRESSION HAS VALUE

cout << age cout

STATEMENT

cout << “You are ” << age << “ years old\n” ;

Manipulators • Manipulators are expressions that affect the

state of an output stream

• endl, fixed, showpoint, setw, and setprecision are manipulators that can be used to control output format

• endl is use to terminate the current output line, and create blank lines in output – same effect as the ‘\n’ character

Using Manipulatorsfixed and showpoint

• Use the following statement to specify that (for output sent to the cout stream) decimal format (not scientific notation) be usedcout.setf(ios::fixed);

• Use the statement below to specify that a decimal point be included (even for floating values with 0 as fractional part) cout.setf(ios::showpoint);

• Together, these two statements ensure that output of floating-point numbers will be uniform for the duration of the program (or until the settings are changed by a subsequent statement or statements)

setprecision(n)• requires #include <iomanip.h> and appears in an

expression using insertion operator (<<)

• if fixed has already been specified, argument n determines the number of places displayed after the decimal point for floating point values

• remains in effect until explicitly changed by another call to setprecision

What is exact output?

#include <iomanip.h> // for setw( ) and setprecision( )#include <iostream.h>#include <stdlib.h>

int main ( ){ float myNumber = 123.4587 ;

cout.setf(ios::fixed); // use decimal format cout.setf(ios::showpoint); // print decimal points

cout << “Number is ” << setprecision ( 3 ) << myNumber << endl ;

system(“PAUSE”); return 0 ;}

Manipulator setw

• “set width” lets us control how many character positions the next data item should occupy when it is output

• setw is only for formatting numbers and strings, not char type data

setw(n)• requires #include <iomanip> and appears in an

expression using insertion operator (<<) • argument n is called the fieldwidth

specification, and determines the number of character positions in which to display a right-justified number or string (not char data). The number of positions used is expanded if n is too narrow

• “set width” affects only the very next item displayed, and is useful to align columns of output

What is exact output?#include <iomanip.h> // for setw( )#include <iostream.h>#include <stdlib.h>

int main ( ){ int myNumber = 123 ; int yourNumber = 5 ;

cout << setw ( 10 ) << “Mine” << setw ( 10 ) << “Yours” << endl;

<< setw ( 10 ) << myNumber<< setw ( 10 ) << yourNumber << endl ;

system(“PAUSE”); return 0 ;}

What is exact output?#include <iomanip.h> // for setw( ) and setprecision( )#include <iostream.h>#include <stdlib.h>

int main ( ){ float myNumber = 123.4 ; float yourNumber = 3.14159 ;

cout.setf(ios::fixed); // use decimal format cout.setf(ios::showpoint); // print decimal points cout << “Numbers are: ” << setprecision ( 4 ) << endl << setw ( 10 ) << myNumber << endl

<< setw ( 10 ) << yourNumber << endl ;

system(“PAUSE”); return 0 ;}

float x = 312.0 ; float y = 4.827 ;

cout.setf(ios::fixed); cout.setf(ios::showpoint);

cout << setprecision (2) << setw (10)<< x << endl << setw (10) << y<< endl << endl;

cout << setprecision (1) << setw (10)<< x << endl << setw (10) << y<< endl << endl ;

cout << setprecision (5) << setw (7)<< x << endl << setw (7) << y<< endl ;

More Examplesx

312.0

y

4.827

312.00 4.83

312.0 4.8

312.000004.82700

Keyboard input

• Object cin represents the input stream• The extraction operator takes data from the stream

and puts it in a variable:int x; // variable declarationcout << “Enter a number: ”; // promptcin >> x; // readcout << “You entered: ” << x << endl; // echo

• Although input can be chained, this is not advisable with interactive programming

Keyboard input

• General syntax:cin >> variable;

• The only thing that can go on the right of the extraction operator is a variable – stores data extracted from the input stream

Extraction and white space

• The >> operator reads, but does not store as data, any leading white space characters

• White space characters include:– Spaces– Tabs– Newline characters

• To the extraction operator, such characters are delimiters – they define where one data item ends and the next one begins

• This means space characters aren’t considered data by the extraction operator, even if the data type of the destination variable is char

STATEMENTS CONTENTS MARKER POSITION

int i ; 25 A\n char ch ; 16.9\n float x ; cin >> i ; 25 A\n

16.9\n

cin >> ch ; 25 A\n 16.9\n

cin >> x ; 25 A\n 16.9\n

Example

i ch x

25

25 ‘A’

i ch x

i ch x

i ch x

16.925 ‘A’

NOTE: shows the location of the file reading marker

Example

char first,middle,last;

cin >> first;cin >> middle;cin >> last;

Suppose the user types:ABC

What is stored in the variables?

What if the user types:A B C

Example

int age;char initial;double bill;

cin >> age;cin >> initial;cin >> bill;

What is stored in the variables if the user types:25 J 2

What if the user types:2 25 J

What about:J 25 2

Weakness of extraction

• The extraction operator works fine as long as a program’s user provides the right kind of data – a number when asked for a number, for example

• If erroneous data is entered (a letter instead of a number, for example), the extraction operator isn’t equipped to handle it; instead of reading the data, it shuts down the input stream, and no more data can be read from it

Reading char data with the get() function

• An alternative to the >> operator is the get() function, a member of the istream class

• Like all member functions, get() can only be called by an object of its class type – a familiar instance of this class is cin

• The get() function reads and stores the next character in the input stream, skipping nothing – in other words, it reads white space

Example

#include <iostream.h>#include <stdlib.h>

int main(){

char c;cout << “Enter a character: ”;cin.get(c); // reads the character enteredcout << “You entered: ” << c << endl;system(“PAUSE”);return 0;

}

Weakness of get()

• In the previous example, a single character is read and echoed to the screen

• The next example attempts to do the same thing, only with two characters, but it doesn’t work

• Take a look at the code – what is output?

Example#include <iostream.h>#include <stdlib.h>

int main(){

char c, d;cout << "Enter a character: ";cin.get(c); // reads the character entered

cout << "Enter another character: "; cin.get(d); cout << "You entered: " << c << " and " << d << endl;

system("PAUSE");return 0;

}

char first ; char middle ; char last ;

cin.get ( first ) ; cin.get ( middle ) ; cin.get ( last ) ;

NOTE: The file reading marker is left pointing to the space after the ‘B’ in the input stream.

first middle last

At keyboard you type: A[space]B[space]C[Enter]

first middle last

‘A’ ‘ ’ ‘B’

The ignore() function

• Because get() reads all characters, including white space, there is no way to avoid reading spaces, newlines, etc.

• This is fine if you want to read these characters, but it is problematic in many instances, as we have seen

• To remedy this situation, use the ignore() function to skip unwanted characters, as described on the next several slides

The ignore() function

• Like get(), ignore() is a member function of the istream class

• A call to ignore from the cin object can take two forms; the simpler form is:cin.ignore();– this form means ignore the next character in the stream– it is useful to place a call like this after each input

statement (cin.get() or extraction) in a program that uses any calls to cin.get() – this will clean up any lingering newline characters in the input stream

Revised example#include <iostream.h>#include <stdlib.h>

int main(){

char c, d;cout << "Enter a character: ";cin.get(c); // reads the character enteredcin.ignore(); // throws away the newline character

cout << "Enter another character: "; cin.get(d);

cin.ignore(); cout << "You entered: " << c << " and " << d << endl;

system("PAUSE");return 0;

}

Other forms of ignore()

• You can also choose to call ignore() with one or two argument(s); using this form, you can specify how many characters to ignore, and/or the last character in a series of characters to ignore

• The example on the next slide illustrates these two forms

Examplechar c, d, e;cout << "Enter a character: ";cin.get(c); // reads the character enteredcin.ignore(1); // discards the newline charactercout << "Enter another character: ";cin.get(d);cin.ignore(100, '\n'); // discards next 100 characters or

// next newline, whichever comes firstcout << "Enter one more character: ";cin.get(e);cin.ignore(); // discards newlinecout << "You entered: " << c << ", " << d << " and " << e << endl;

EXAMPLE

string message ; cin >> message ; cout << message ;

HOWEVER . . .

String Input in C++

Input of a string is possible using the extraction operator >>.

Extraction operator >>

• When using the extraction operator ( >> ) to read input characters into a string variable: – the >> operator skips any leading whitespace

characters such as blanks and newlines– it then reads successive characters into the

string, and stops at the first trailing whitespace character (which is not consumed, but remains waiting in the input stream)

Example

string name;cout << “Enter your name: ”;cin >> name;cout << “You entered: ” << name << endl;

Output:

Enter your name: Cate ShellerYou entered: Cate

getline( ) Function

• Because the extraction operator stops reading at the first trailing whitespace, >> cannot be used to input a string with blanks in it

• use getline function with 2 arguments to overcome this obstacle

• First argument is an input stream variable, and second argument is a string variable

EXAMPLE

string message ;

getline (cin, message ) ;

getline(istream, string)

• getline does not skip leading whitespace characters such as blanks and newlines

• getline reads successive characters (including blanks) into the string, and stops when it reaches the newline character ‘\n’

• the newline is consumed by getline, but is not stored into the string variable

Example

string name;cout << “Enter your name: ”;getline(cin, name);cout << “You entered: ” << name << endl;

Output:

Enter your name: Cate ShellerYou entered: Cate Sheller

File I/O

• When reading data from a file, the programmer doesn’t need to be concerned with interacting with a user

• This means prompts are unnecessary, and more than one piece of data can be extracted from the input stream using a single line of code

• To achieve these relative freedoms requires a little extra work up front, however

Diskette Files for I/O

your variable

(of type ifstream)

your variable

(of type ofstream)

disk file“A:\myInfile.dat”

disk file“A:\myOut.dat”

executingprogram

input data output data

#include <fstream.h>

To Use Disk I/O, you must• Use #include <fstream.h> as well as <iostream.h>• Choose valid identifiers for your filestream objects

and declare them– ifstream for input files– ofstream for output files

• Open the files and associate them with disk names• Use your filestream objects in your I/O statements

(using >> and << , manipulators, get, ignore, getline)• Close the files

Statements for Using Disk I/O#include <fstream.h>…

ifstream myInfile; // declarations for file// stream objects

ofstream myOutfile;

myInfile.open(“A:\\myIn.dat”); // open filesmyOutfile.open(“A:\\myOut.dat”);

… // read and write data

myInfile.close( ); // close filesmyOutfile.close( );

Using file stream object for input

• Once an ifstream object has been opened, can use it just as you would cin; example:ifstream inFile;

int x, y, z;

string s;

char c;

inFile.open(“a:\\input.txt”);

inFile >> x >> y >> z; // reads 3 numbers from file

inFile.get(c); // reads char from file

inFile.ignore(); // discards next character

getline(inFile, s); // reads string from file

Using file stream object for output

• An ofstream object, once opened, works like cout; example:ofstream output;

output.open(“a:\\myoutfile.txt”);

output.setf(ios::fixed);

output.setf(ios::showpoint);

output << setprecision(2) << setw(6) << 3.14159 << endl;

What does opening a file do?• Associates the C++ identifier for your file with the

physical (disk) name for the file• Places a file reading marker at the very beginning

of the file, pointing to the first character in it• If the input file does not exist on disk, open is not

successful• If the output file does not exist on disk, a new file

with that name is created; if the output file already exists, it is erased

Stream Fail State• When a stream enters the fail state, further I/O

operations using that stream have no effect at all. But the computer does not automatically halt the program or give any error message

• Possible reasons for entering fail state include: • invalid input data (often the wrong type) • opening an input file that doesn’t exist • opening an output file on a diskette that is

already full or is write-protected