Download presentation
Presentation is loading. Please wait.
Published byFelicity Parrish Modified over 9 years ago
1
C++ Vs. Java Who will win?
2
Look Ma, no classes! C++ was conceived as an object-oriented extension to C C was (is) purely procedural language –Functions –Functions (methods) separate from data –Complex data structures exist that are not objects non- memberEntire programs can be written using only non- member functions, or (almost) only classes, or (most commonly) some mixture
3
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
4
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
5
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 implicit type coercion –This is called implicit type coercion explicit type casting –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 –Any other value is true
6
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
7
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 preprocessor directiveAccess to libraries via preprocessor directive #include header file object fileThe #include directive is tied to a header file and an object file
8
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
9
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
10
Simple C++ program example #include 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; }
11
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
12
Preprocessor directives The first line of code in the example program: #include –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
13
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)
14
Input/output in C++ operatorsI/O operations are performed by operators (not methods or functions, per se) –Insertion operator –Insertion operator (<<) does output –Extraction operator –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
15
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
16
<< is a binary operator << is called the output or insertion operator << is left associative EXPRESSIONHAS VALUE cout << age cout STATEMENT cout << “You are ” << age << “ years old\n” ;
17
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
18
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)
19
setprecision(n) requires #include 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
20
What is exact output? #include // for setw( ) and setprecision( ) #include 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 ; }
21
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
22
setw(n) requires #include 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
23
What is exact output? #include // for setw( ) #include 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 ; }
24
What is exact output? #include // for setw( ) and setprecision( ) #include 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 ; }
25
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 Examples x 312.0 y 4.827 312.00 4.83 312.0 4.8 312.00000 4.82700
26
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
27
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
28
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
29
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 ichx 25 ‘A’ ichx i x i x 16.925‘A’ NOTE: shows the location of the file reading marker
30
Example charfirst, middle, last; cin >> first; cin >> middle; cin >> last; Suppose the user types: ABC What is stored in the variables? What if the user types: ABC
31
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
32
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
33
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
34
Example #include int main() { char c; cout << “Enter a character: ”; cin.get(c);// reads the character entered cout << “You entered: ” << c << endl; system(“PAUSE”); return 0; }
35
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?
36
Example #include 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; }
37
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. firstmiddlelast At keyboard you type: A [ space]B [ space ] C [ Enter] firstmiddlelast ‘A’‘ ’‘B’
38
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
39
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
40
Revised example #include 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; }
41
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
42
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;
43
EXAMPLE string message ; cin >> message ; cout << message ; HOWEVER... String Input in C++ Input of a string is possible using the extraction operator >>.
44
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)
45
Example string name; cout << “Enter your name: ”; cin >> name; cout << “You entered: ” << name << endl; Output: Enter your name: Cate Sheller You entered: Cate
46
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 ) ;
47
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
48
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
49
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
50
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” executing program input dataoutput data #include
51
To Use Disk I/O, you must Use #include as well as 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
52
Statements for Using Disk I/O #include … 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( );
53
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
54
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;
55
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
56
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.