Overview of C++ Kernel Language. Overview zTokens zTypes ytype conversions and casts zExpressions...
-
Upload
todd-sparks -
Category
Documents
-
view
218 -
download
0
Transcript of Overview of C++ Kernel Language. Overview zTokens zTypes ytype conversions and casts zExpressions...
Overview of C++Kernel Language
Overview
TokensTypes
type conversions and castsExpressionsStatementsC++ preprocessorInput and output
Tokens
The smallest elements of a program
ASCII characters Five types of
tokens
LiteralsIdentifiersKeywordsOperators and
PunctuatorsComments
Identify the Tokens
#include <iostream> // C++ standard I/O
int main(int argc, char *argv[]) {
if (argc > 1)
cout << “Hello, ” << argv[1];
else
cout << “Hello, World”;
cout << endl;
}
keyword
comment
operator
literal
identifier
Literals
Constant of any C++ native typeExamples:
3 // an integer literal 3L // a long integer true // a boolean literal 5.0 // a floating-point number “5” // the string constant 5 L’abc’ //a wide character (wchar_t)
constant
Literal character constants
‘\a’ alert ‘\\’ backslash ‘\b’ backspace ‘\r’ carriage return ‘\”’ double quote ‘\f’ formfeed ‘\t’ tab ‘\n’ newline ‘\0’ null character
‘\’’ single quote ‘\v’ vertical tab ‘\101’ octal (ascii ‘A’) ‘\x041’ hexadecimal
(ascii ‘A’) L’oop’ wchar_t
constant
Identifiers
Usually variable namesSequences of letters, digits, and
underscoresStart with letter or underscoreNaming conventions
very_long_identifier // C and Unix style veryLongIdentifier // Pascal style C++ naming conventions more complex than C
Keywords
Reserved words; cannot be identifiers int int; // not a valid identifier name
46 in C++ vs. 32 in C
Common C++ keywordsasm, auto, bool, break, case, catch, char, class,const, const_cast, continue, default,delete, do, double, dynamic_cast, else, enum, explicit, extern, false, float, for, friend, goto,if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef,typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while
Operators and Punctuators
Operators on native types similar to C arithmetic operators + - * / % pointer and member operators -> ->* logical operators && || ! assignment operators = += *=, etc. relational operators > < == != >= <=
C++ operator overloading
Operators can be (re)defined for user types! Example:
define + for vectorsdefine + for matricesdefine + for complex numbers
Some new operators :: scope resolution
Native C++ Types
boolchar, wchar_t
modified with signed or unsignedint
modified with signed or unsigned can be modified with short or long int can be dropped! long num; can be modified with const or volatile
float double long double
Native C++ Types: Bottom Line
boolcharint unsigned longfloat doublepitfalls
size is machine-dependent sizeof(‘a’) == sizeof(int) in C, but sizeof(char) in C++ (char is smaller than int)
Type Size
Language standard does not define the size of native types
sizeof(type) operatorlimits.h and float.h
Defines the largest and smallest type values
include <limits>
numeric_limits<type>::max()
Implicit conversions (coercion)
Occur in mixed expressionsWidening conversions:
int < unsigned < long < unsigned long < float < double < long double
Widening safe, narrowing unsafe.But: narrowing conversions allowed
with assignments
Coercion Examples
int i;
long j = 3;
float f = 2.3;
char c = ‘P’;
i = c; // char promoted to int
j = c + 7; // result to long
f = i + j; // result to float
j = f + i; // dangerous: float
// truncated to long
Explicit conversions (casts)
C and older C++: unrestricted casts (type)expr type(expr)
static_cast: safe, portable, invertible static_cast<char>(‘A’ + i)
reinterpret_cast: implementation- and system-dependent reinterpret_cast<int>(&x)
will talk about two more kinds of casts later
Enumeration TypesNamed integer constantsenum Animal {Cat, Dog, Horse = 5};
Tag name, enumerators must be uniqueImplicit conversion to integer
int i = Dog; // assigns 1 to iExplicit cast from integer
Animal anim = static_cast<Animal>i;
C++ trick: enum {SIZE = 100};
replaces #define SIZE 100
Expressions
Precedence Prioritize among multiple operators (a*=5-3) Learn through experience, use () to be safe
Associativity Associate operands with operators Left to right: most common Right to left: mainly for assignment operators
User-defined operators cannot change these!
Expression Examples
You must know the operator hierarchy to evaluate an expression like this:
3 < 4 && 4 > 5 || 2 < 4; // bool
int i = 2;
1 + i++ + 3; // int
Operator hierarchy
Postfix operators: (), [], ->, .Postfix increment, decrement ++, --Unary operators: sizeof, +, -, !, &, *, ~Binary operators: (*, /, %), (+, -), (<<, >>),
(<,<=,>,>=),(==, !=),(&),(^), (|),(&&),(||)Ternary operators: ?:Assignment: =, +=, -=, *=, /=, %=Comma: ,
Assignment Expression
Modifies the left-hand side f = (a + b) * c;
Also works as an expression f = (a=b)*c; a = b = c = d = e = 4; //right-associative a = (b = ( c = (d = (e = 4))));
Returns value assignedPitfall: assignment (=) vs equality (==)
if (a = 1) // always succeeds if (a == 1) // might succeed
C++ Statements Overview
Expressions expression ; compound
Conditional if/if-else
Iteration while for do (not as common as iteration)
switch/case Formatting conventions
C++ Statements
i = j+k*(p-q);
f = fun1() + fun2();
i = 5;j = ++i;
{ i = 12; j = i + 7;}
Expression ;
Statements (Cont.)
if AND if-else
if (expression) statement
if (expression) statementelse statement
if (2==a) j = function1(2,4);
if (ptr != 0) a = ptr->value;else { reportError(); cleaup(); exit(2);}
Statements (Cont.)
while
while (expression) statement
while ((ptr != 0) && (ptr->value!=target)) { ptr = ptr->next;}
Statements (Cont.)
forfor (expr1; expr2; expr3) statement
for (int i=0; i<limit; i++) { doSomething(i); doMore(i);}doEvenMore(i); // Is i defined here ?
Statements (Cont.)
do
do statementwhile (expression);
do { cout << “Input a number:”; cin >> x;}while (x==0);
Statements (Cont.)
switchswitch (expression) statement
switch (grade) { case ‘a’:
aGrades++; break; case ‘b’:
bGrades++; break; case ‘c’:
cGrades++; break; default: fails++;}
Statements (Cont.)
break, continue
while (i<limit) { j=fun1(i); if (j==fail) break; doMore(i);}
while (i<limit) { j=fun1(i); if (j==fail) continue; doMore(i);}
C++ Preprocessor
#include lives on#include <iostream> // note no .h
#define less useful prevent including a file twice
#ifndef __INCLUDENAME_H_
#define __INCLUDENAME_H_
// body of include file here
#endif
C++ Preprocessor:#define vs. consts
const float pi = 3.14;
typed constantconst int SIZE = ROWS*COLS;
value computed by compiler expression evaluator
const int SIZE = 200;
Compiler will complainconst redefinition not
allowed
#define pi 3.14
untyped constant#define SIZE ROWS*COLS
value computed by textual substitution by preprocessor
#define SIZE 200
warning at bestsize redefinition!
C++ Preprocessor: macros vs. inline functions
inline int square(int x) {
return x*x;
} standard procedure call
semantics cout << square(x++); x incremented once
Typed need square for ints,
floats explicit error when
compiling square(“abc”)
#define square(x) \ ((x)*(x))
semantics determined by syntactic substitution cout << square(x++); x incremented twice!
Untyped works with ints, floats, … square(“abc”)
might not compile, but...
Input/Output in C++
C++ iostream.h instead of stdio.hWhy change?
Input/output routines in iostream can be extended to new types declared by the user
The routines are in some senses easier to use Some aspects of the routines can be set without
having to repeat them (e.g., setting the desired precision for printing floating point values)
Readings: 2.1-2.11, 15.1-15.4, 17.1-17.8, 16.1-16.7, 18.1-18.6
OutlineSimple input/output (iostream.h)
cout, cin, cerroutput
insertion operator (<<) and chainingint, float, string
inputextraction operator (>>) and chainingint string
Advanced input/outputobject flags (setf, unsetf)input status bitsmanipulators (iomanip.h)file input/output (fstream.h)
opening/closing files
Input/Output
The C I/O library stdio.h is available printf, fprintf, etc. Do not use them in this course !
The C++ library iostream.h is better Type-safe Extensible Easier to use
Using iostream.h
Include iostream.h instead of stdio.hStandard iostream objects:
cout - object providing a connection to the monitorcin - object providing a connection to the keyboardcerr - object providing a connection to error streem
To perform input and output we send messages to one of these objects (or one that is connected to a file)
Iostream Basics
<< is "put to" (insertion) operator>> is "get from" (extraction) operatorThree standard streams: cout, cin, cerrAll native types and string support
<< and >> These operators can be defined for user
types! Matrix m(5,5); cout << m;
The Insertion Operator (<<)
To send output to the screen we use the insertion operator on the object cout
Format: cout << Expression;The compiler figures out the type of the
object and prints it out appropriatelycout << 5; // Outputs 5
cout << 4.1; // Outputs 4.1
cout << “String”; // Outputs String
cout << ‘\n’; // Outputs a newline
The Extraction Operator (>>)
To get input from the keyboard we use the extraction operator and the object cin
Format: cin >> Variable;No need for & in front of variableThe compiler figures out the type of the
variable and reads in the appropriate typeint X;float Y;cin >> X; // Reads in an integercin >> Y; // Reads in a float
Chaining Calls
Multiple uses of the insertion and extraction operator can be chained together:cout << E1 << E2 << E3 << … ;
cin >> V1 >> V2 >> V3 >> …;
Equivalent to performing the set of insertion or extraction operators one at a time
Examplecout << “Total sales are $” << sales << ‘\n’;cin >> Sales1 >> Sales2 >> Sales3;
Basic I/O Example#include <iostream.h>
#include <string>
int main() {
int x, y, z;
cin >> x >> y >> z;
cout << x << endl << y << endl << z;
char word1[512];
string word2;
// reads two words separated by whitespace
cin >> word1 >> word2;
cout << word1 << ‘+’ << word2 << endl;
}
Setting the Width
You can use the width(int) function to set the width for printing a value, but it only works for the next insertion commandint x = 42;
cout.width(5);
cout << x << ‘\n’; // Outputs 42
cout << x << ‘\n’; // Outputs 42
Setting the Fill Character
Use the fill(char) function to set the fill character. The character remains as the fill character until set again.int x = 42;
cout.width(5);
cout.fill(‘*’);
cout << x << ‘\n’; // Outputs ***42
Significant Digits in Float
Use function precision(int) to set the number of significant digits printed (may convert from fixed to scientific to print):float y = 23.1415;
cout.precision(1);
cout << y << '\n'; // Outputs 2e+01
cout.precision(2);
cout << y << '\n'; // Outputs 23
cout.precision(3);
cout << y << '\n'; // Outputs 23.1
Additional I/O Methods istream.get
Reads a single character from input Including white space
int main() {
int ch;
while ( (ch = cin.get()) != EOF)
cout.put(ch);
}
istream.getline(char *buf, int limit, char delim); Reads line of input up to limit or delim
ManipulatorsA manipulator is a simple function that
can be included in an insertion or extraction chain
C++ manipulators must include iomanip.h to use several are provided to do useful things you can also create your own (see 17.3, 17.5,
17.6, 17.8)
Output Manipulators (no args)
Manipulators included like arguments in extractionendl - outputs a new line character, flushes outputdec - sets int output to decimalhex - sets int output to hexadecimaloct - sets int output to octal
Example:#include <iostream.h>#include <iomanip.h>int x = 42;cout << oct << x << endl; // Outputs 52\ncout << hex << x << endl; // Outputs 2a\ncout << dec << x << endl; // Outputs 42\n
Output Manipulators (1 arg)
Manipulators taking 1 argumentsetw(int) - sets the width to int valuesetfill(char) - sets fill char to char valuesetprecision(int) - sets precision to int valuesetbase(int) - sets int output to hex if int is 16,
oct if int is 8, dec if int is 0 or 10setiosflags(flags) - set flags onresetiosflags(flags) - sets flags off
cout << setw(7) << setprecision(2) << setfill(‘_’) << 34.267 << endl; // outputs __34.27
Input Status Flags
When performing input, certain problems may occur, we can determine if an error has occurred by checking these flags:eof() - end-of-file occurred during inputfail() - input operation failedgood() - no flags set (not eof or any of fail flags)
Flags stay set and all input fails until clear() function called
Testing Status Flags
int x;
int total = 0;
cin >> x;
while (!cin.eof()) {
total += x;
cin >> x;
}
cout << “Total is “ << total << endl;
Testing Status Flags
Extraction is an operator, returns cin object (can check eof() or other flags after operation):
int x;
int total = 0;
while (!(cin >> x).eof())
total += x;
cout << “Total is “ << total << endl;
Integer Input
If none of the flags hex, dec, oct set then we can indicate how an int is formatted with value typed:42 - decimal 42052 - octal 520x2a - hexadecimal 2a
If any of these flags set, all input will be treated as being of only that type note, in explicit decimal format, 052 read as 52,
0x2a read as 0
Character Input
The extraction operator when applied to a character ignores whitespace
To read any character use the get(char) function, can also provide no argument (works like getchar)char ch;
cin >> ch; // Reads next non-whitespace char
cin.get(ch); // Reads next character (any)
while (cin.get() != ‘\n’); // Reads to newline
String Input
Can use arguments of string type like any other variable like scanf with %s reads as many chars as typed
(may be too many) can control by using width(int) function or setw(int)
manipulator ignores leading whitespace stops at first whitespace
Example#include <string>string line;
cint >> setw(100) >> line;
String Input with Whitespace
Use function get(stringloc,size,delimitchar) reads string into array at stringloc taking in at most
size chars and stopping at delimitchar (default is ‘\n’ -- you can leave delimitchar off)
stops before delimitchar
Use function getline to also read newline characterExample:
string line;
cin.get(line,100,’\n’); // or
cin.get(line,100);
File I/O
Ability to read/write files Same usage and functions as standard I/O
User must create (open) the streams manually Must include both iostream and fstream
Input ifstream
Output ofstream
Both fstream
File Input/Output
Done with the same operations (insertion, extraction) as keyboard input and monitor output
Simply open input or output object with connection to a file and use it where you would use cin or cout
To use include <fstream.h> create input object of type ifstream or output object of type ofstream
Opening Files
Use open function or include file name when declaring variable:ifstream inobj1;inobj1.open(“in1.dat”)ifstream inobj2(“in2.dat”);
To check if file successfully opened check object in condition:if (!inobj1) cout << “Unable to open file in1.dat” << endl;
Closing a File
Use close() on object to close connection to file:
ifstream in(“in.dat”);…in.close();
File Example#include <stdlib.h>#include <iostream.h>#include <fstream.h>
void main() { char infname[101]; char outfname[101]; char buffer[101];
cout << ”File to copy from: "; cin >> infname; ifstream in(infname); if (!in) { cout << "Unable to open " << infname << endl; exit(0); }
File Example (cont) cout << "File to copy to: "; cin >> outfname; ofstream out; if (!out) { cout << "Unable to open " << outfname << " -- already
exists!" << endl; exit(0); } in.getline(buffer,100); while (!in.eof()) { out << buffer << endl; in.getline(buffer,100); } in.close(); out.close();}
File input approaches
#include <iostream>
#include <fstream>
int main() {
ifstream in(“file.in”);
if (!in)
exit(1);
string str, line;
in >> str; // read word
// read line
getline(cin, line);
in.close(); // close file
}
#include <iostream>
#include <fstream>
int main() {
ifstream in;
in.open(“file.in”);
if (in.fail()) exit(1);
.
.
.
}
File Output
#include <iostream>
#include <fstream>
int main() {
ofstream out(“file.out”);
if (!out)
exit(1);
out << “Written”;
out.close(); // close file
}
#include <iostream>
#include <fstream>
int main() {
ofstream out; out.open(“file.out”);
if (out.fail())
exit(1);
.
.
.
.
}