Sunteți pe pagina 1din 56

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++ isnt 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++ isnt 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 isnt 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
Javas 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 C++
byte (signed, 8 bits) char (sort of)
short (signed, 16 bits) int, short
int (signed, 32 bits) long, int
long (signed, 64 bits) long
boolean (true/false) bool
char (16 bits, Unicode) char (sort of - 8 bit ASCII)
float (32 bits) float
double (64 bits) double
void void
String string
Note: string type is not primitive, built-in type in either language
Notes on C++ data types
Language specification doesnt 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>
isnt, 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 Javas 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 ;
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 Manipulators
fixed and showpoint
Use the following statement to specify that (for output
sent to the cout stream) decimal format (not scientific
notation) be used
cout.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 ;
}
312.0 More Examples 4.827
x y

float x = 312.0 ;
float y = 4.827 ;

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

cout << setprecision (2) << setw (10) 312.00


<< x << endl << setw (10) << y 4.83
<< endl << endl;
cout << setprecision (1) << setw (10)
<< x << endl << setw (10) << y 312.0
<< endl << endl ; 4.8
cout << setprecision (5) << setw (7)
<< x << endl << setw (7) << y 312.00000
<< endl ;
4.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 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 arent considered data by the
extraction operator, even if the data type of the destination
variable is char
Example
NOTE: shows the location of the file reading marker

STATEMENTS CONTENTS MARKER


POSITION
int i; 25 A\n
char ch ; 16.9\n
float x ; i ch x
cin >> i ; 25 25 A\n
16.9\n
i ch x
cin >> ch ; 25 A 25 A\n
16.9\n
i ch x
cin >> x ; 25 A 16.9 25 A\n
16.9\n
i ch x
Example
char first, Suppose the user types:
middle, ABC
last; What is stored in the variables?

cin >> first;


What if the user types:
cin >> middle;
A B C
cin >> last;
Example
int age; What is stored in the variables if the user types:
char initial; 25 J 2
double bill;
What if the user types:
cin >> age; 2 25 J
cin >> initial;
cin >> bill; What about:
J 25 2
Weakness of extraction
The extraction operator works fine as long as a
programs 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 isnt
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
doesnt 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;
}
At keyboard you type:
A[space]B[space]C[Enter]
char first ;
char middle ;
char last ; first middle last

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

NOTE: The file reading marker is left pointing to the


space after the B in the input stream.
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;
}
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
Example
char c, d, e;
cout << "Enter a character: ";
cin.get(c); // reads the character entered
cin.ignore(1); // discards the newline character
cout << "Enter another character: ";
cin.get(d);
cin.ignore(100, '\n'); // discards next 100 characters or
// next newline, whichever comes first
cout << "Enter one more character: ";
cin.get(e);
cin.ignore(); // discards newline
cout << "You entered: " << c << ", " << d << " and " << e << endl;
String Input in C++
Input of a string is possible using the extraction
operator >>.

EXAMPLE
string message ;
cin >> message ;
cout << message ;
HOWEVER . . .
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
doesnt 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

#include <fstream.h>

input data output data

disk file executing disk file


A:\myInfile.dat program A:\myOut.dat

your variable your variable

(of type ifstream) (of type ofstream)


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 files
myOutfile.open(A:\\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(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 doesnt exist
opening an output file on a diskette that is
already full or is write-protected

S-ar putea să vă placă și