c++ vs. java - kirkwood community college+vsjava.pdf · c++ vs. java who will win? ... structure of...

41
C++ Vs. Java Who will win?

Upload: phungminh

Post on 15-Apr-2018

229 views

Category:

Documents


6 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

– Functions (methods) separate from data

– Complex data structures exist that are not objects

• Entire programs can be written using only non-

member 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 coercion

– Can still do explicit type casting, as we do with Java

• Boolean values (true and false) are represented as int values

– 0 is false

– Any 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 directive

#include

• The #include directive is tied to a header file and

an object file

Java data types and their C++

counterparts • Java

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

void

String

• C++

char (sort of)

int, short

long, int

long

bool

char (sort of - 8 bit ASCII)

float

double

void

string

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-specific

return 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 operators (not

methods or functions, per se)

– Insertion operator (<<) does output

– Extraction 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” ;

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 declaration

cout << “Enter a number: ”; // prompt

cin >> x; // read

cout << “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.9 25 ‘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 entered

cout << “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;

}

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 entered

cin.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;

}

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 Sheller

You 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 Sheller

You 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

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 << , 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(“c:\\myIn.dat”); // open files

myOutfile.open(“c:\\myOut.dat”);

… // read and write data

myInfile.close( ); // close files

myOutfile.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(“c:\\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

inFile.close();

Using file stream object for output

• An ofstream object, once opened, works

like cout; example:

ofstream output;

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

output << 3.14159 << endl;

output.close();