C++ Programming Basics and Syntax Guide
C++ Programming Basics and Syntax Guide
Identifiers
These are ANSI C++ reserved words and cannot be used as variable names.
asm, auto, bool, break, case, catch, char, class, const, const_cast, continue,
defaulicadel e tesidomdotibleSFd ynamid CRCaS R | SeMEEn
G e X P 1H CHtNC cc Nt al SEN ' ab
fors friend igoton Hif@ dnline, Hnt M onghi¥mutabl'e SMnamespace; ¥new f'operator W privace;
protected MpublE CEEre S TE TN terpre tROaS T e Gt NEChoTRS ToncedS S0MRS ta t1ch
StaticEcastastructs switchistemplates ithd SERthrow St rue Sty typedei typedd),
typename, union, unsigned. using, virtual. void. volatile. wchar_t
Character Strings
The string "Hello" is actually composed of 6
characters and is stored in memory as follows:
ANSI C++ Library Files
Char H e 1 1 o \O The following files are part of the ANSI C++
Index 0 1 2 3 4 5 standard and should work in most compilers.
\O (backslash zero) is the null terminator character <alllooEtchnMh>E<hiiESciElh>W<dcqlicHli>
and determines the end of the string. A string is an <exception.h> <fstream.h> <functional.h>
array of characters. Arrays in C and C++ start at <iomanip.h> <ios.h> <diosfwd.h>
zero. <iostream.h> <istream.h> <iterator.h>
Sie = “aleilierd <limits.h> <list.h> <locale.h> <map.h>
str[2] = 'e’'; // string is now ‘Heelo’
<memory.h> <new.h> <numeric.h>
common <sftring.h> functions: <ostream.h> <queue.h> <set.h> <sstream.h>
strcat(s7,s2) strchr(s7,c) strcmp(s7,s2) <stack.h> <stdexcept.h> <streambuf.h>
strepy(s2,s7) strlen(s7) strncpy(s2,s7,n) <strdngfhi>S<typeinfofh> <ttty
Th>
strstr(s7,s2) <valarray.h> <vector.h>
Control Structures Console Input/Output
Decision (if-else) [See File I/0 on reverse for more about streams]
Be (@enelliclen) 4 C Style Console 1/0
statements; stdin — standard input stream
} stdout — standard output stream
else if (condition) ({ stderr — standard error stream
statements; // print to screen with formatting
} pranth(@fcriacilz s a2k
else { printt (TnOmsST %0 ki kc:SIS EEEC
&
statements; //_print to/string s
B Cioelnme(S, weigizie , @l @EEE,
.. .) !
if (x == 3) // curly braces not needed sprintf (SETRTSITSNST Tha W kIR0
)&
flag = 1; // when if statement is // read data from keyboard into
else // followed by only one // namel name2, ...
flag = 0; // statement scanf ("format" , &namel , &name2, ...)
Repetition (while) scanf ("%d ,%f” ,varl ,var2) ; // read nums
while (expression) { // loop until //greaditroniisStringyis
statements; // expression 1is false sscanf (“format" , &namel , &name2, ...)
K SScant (S ki xc At IBvar2)s
Repetition (do-while) C Style 1/0 Formatting
do { // perform the statements %d, %1 dinteger
statements; // as long as condition %c single character
} while (conddtdion). // is true double (float)
Repetition (for) octal
init - initial value for loop control variable pointer
condition - stay in the loop as long as condition unsigned
is true char string
increment - change the loop control variable exponential
fbr(init; @royitelil it @i increment) { hexadecimal
statements; number of chars written
} %g, %G same as f for e,E
Bifurcation (break, continue, goto, exit) C++ console 1/0
break; // ends a loop cout<< console out, printing to screen
continue; // stops executing statements cin>> console in, reading from keyboard
// in current iteration of loop cont- cerr<< console error
// inues executing on next iteration clog<< console log
label: cout<<"Pleaserenter an dnteger:
goto label; // execution continues ac clin=—
1%
// label cout<<'numl: "<<i<<"\n"<<endl;
exit(retcode); // exits program Control Characters
Selection (switch) \b backspace \f form feed \r return
switch (variable) { \' apostrophe \n newline \t tab
case constantl: // chars. ints \nnn character #nnn (octal) \" quote
statements; \NN character #NN (hexadecimal)
break; // needed to end flow
case constantZ:
statements; // allocate memory (C or C++)
break; void * malloc (nbytes); // nbytes=sizo
default: char *buffer; // declare a buffer
statements; // default statemencs // allocate 10 bytes to the buffer
buffer = (char *)malloc(10);
// allocate memory (C or C++)
// nelements = number elements
i
Default Parameter Values second { e var
. aelel (e &, dnE B=2) 1 main () {
T second;
r=a+b: cout << var << endl;
(@) collitm=<M(Var2)<=<Nendis
OF
File 1/0 Stream Pointers
[Link]() returns pointer to current location
#include <fstream.h> // read/write file
when reading a file
#include <ofstream.h> // write file
[Link]() returns pointer to current location
#include <ifstream.h> // read file
when writing a file
File I/O is done from the fstream, ofstream, and
// seek a position in reading a file
ifstream classes.
[Link](position);
[Link](offset, direction);
File Handles
// seek a position in writing a file
A file must have a file handle (pointer to the file) to
[Link] (position) ;
access the file.
[Link] (offset, direction);
ifstream infile; // create handle called
direction can be one of the following
// infile to read from a file
ios: :beg beginning of the stream
ofstream outfile; // handle for writing
ios: :cur current position of the stream pointer
fstream f; // handle for read/write
ios: :end end of the stream
Opening Files
Binary Files
After declaring a file handle, the following syntax
buffer is a location to store the characters.
can be used to open the file
numbytes is the number of bytes to written or read.
void open(const char *fname, ios::mode);
write (char *buffer, numbytes);
fname should be a string, specifying an absolute
read (char *buffer, numbytes);
or relative path, including filename. ios: : mode
can be any number of the following and repeat:
in Open file for reading Output Formatting
streamclass £; // declare file handle
out Open file for writing
ate Initial position: end of file // set output flags
[Link](ios_base:
:flag)
app Every output is appended at the end of file
trunc If the file already existed it is erased possible flags
binary Binary mode dec fixed hex oct
ifstream f; // open input file example scientific internal left right
fifopen( InpucHtXe " os i &Hn)" uppercase boolalpha showbase showpoint
OfiSBREAMEEIN/ O PENN T O T RWI | CIToE NED Ity showpos skipws unitbuf
[Link]("[Link]"”, dos::out | ios::binary adjustfield left | right | internal
| 1os::app); basefield dec | oct | hex
floatfield scientific | fixed
Closing a File £.£i11 () get fill character
£.fill (ch) set fill character ch
A file can be closed by calling the handle's close
function [Link](numdigits) sets the precision for
[Link](); floating point numbers to numdigits
[Link](c) put a single char into output stream
[Link] (flag) sets a flag
Reading From a File (Text Mode)
[Link] (flag, mask) sets a flag w/value
The operator >> can be used to read from a file. It
[Link] () returns the current number of
works similar to cin. Fields are seperated in the file
characters to be written
by spaces.
[Link] (num) sets the number of chars to be
ifstream f; // create file handle
written
[Link]("[Link]”); // open file
while ([Link]()) // end of file test
£8>>05>h>> Ol /e ad N To T as bR o
Operators Precedence
I/0 State Flags
Flags are set if errors or other conditions occur. !+, — (unary operators) first ROl
The following functions are members of the file
object second L tOR
[Link] () returns true if a failure occurs in
reading or writing thid [ tO R
[Link] () returns true for same cases as
fouth L tOR
bad() plus if formatting errors occur
[Link]
() returns true if the end of the file
fith LTtOR
reached when reading
[Link] () returns false if any of the above ssch LtOR
were frue
seventh L tO R
(assignment operator) last RtolL
dec oct|hex|ch dec oct hex|ch dec oct hex ch |dec oct hex ch
0 |0 |60 NUL (null) 32 140 |20 |(space)| 64 |100(40 @ ‘96 140/60 |°
1 |1 |01 |SOH (start of header) 33 |41 |21 |! 65 (10141 |A ]97 14161 |a
2 |2 |02 |STX (start of text) 34 (42 |22 |" 66 10242 (B “98 142|162 b
3 [3 |03 [ETX (end of text) 35 |43 |23 |# 67 10343 |C | 99 14363 |c
4 |4 |04 EOT (end of transmission) 36 44 24 |$ 68 10444 |D ||100|144/64 |d
5 |5 |05 ENQ (enquiry) 37 |45 |25 |% 69 |105|45 (E ||101|/145/65 |e
6 |6 |06 ACK (acknowledge) 38 46 |26 |& 70 (106(46 |F ||102|146/66 f
7 |7 |07 |BEL (bell) 39 (47 |27 | 71 (10747 |G ||103|147|67 |g
8 |10 |08 |BS (backspace) 40 |50 |28 |[( 72 |110(48 H ||104|150(/68 h
9 |11 |09 |HT (horizontal tab) 419 5181298 ) 73 |111|49 |I ||165/151|69 |i
10 |12 |Oa |LF (line feed - new line) 42 |52 |2a |* 74 (112/4a |J ||106|152|6a |j
11 |13 Ob |VT (vertical tab) 43 |53 |2b |+ 75 (113/4b |K |[107|153|6b |k
12 |14 |0c FF (form feed - new page) 44 |54 2¢ |, 76 |114|4c |L ||108|154|6¢c |1
13 |15 |0d |CR (carriage return) 45 |55 |2d |- 77 |115/4d M ||109 155/6d |m
14 |16 0Oe |[SO (shift out) 46 |56 |2e |. 78 |116|4e ”N7 116|/156/6e |n
15 |17 |0f |SI (shiftin) 4] |57 |2f |/ 79 (117(4f |0 ||111|157|6F |o
16 |20 10 |DLE (data link escape) 48 60 |30 |6 80 |120|50 |P ||112|160|70 |p
17 |21 |11 DC1 (device control 1) 49 61 31 |1 81 (12151 |Q |[{113|161|71 |q
18 (22 |12 |DC2 (device control 2) 50 (62 |32 |2 82 [122|52 |R ||114|162|72 |r
19 |23 13 |DC3 (device control 3) 518 6301831 3 881(123531(1S [|115(163|738 [s
20 (24 |14 |DC4 (device control 4) ~ |[52 |64 [34 |4 84 12454 |T ||116|164|74 |t
21 |25 |15 |NAK (negative acknowledge) 538 658358 5 85 [125(55 |U |[117|165|75 |u
22 |26 |16 |SYN (synchronous idle) 54 66 |36 |6 86 |126|56 |V |[118/166|76 |v
23 |27 |17 |ETB (end of transmission block)||55 |67 (37 |7 87 [127|57 |W ||119|167|77 |w
24 |30 |18 |CAN (cancel) 56 (70 |38 |8 |88 [130/58 |X ||/120]170/78 |x
25 |31 |19 |EM (end of medium) 578 7183989 89 [131|59 |Y ||121|171|79 |y
26 |32 |la |SUB (substitute) 58 |72 |3a 90 |132|5a |Z ||122|172|7a |z
27 |33 |1b |ESC (escape) 59873 8li3bl ; 91 |133|5b [7 11231173 7b {
28 (34 |1c |FS (file separator) 60 |74 |3c |< 92 |134|5¢c |\ [|124|174|7c |
29 |35 |1d |GS (group separator) 61 |75 |3d |= 93 |135|5d |1 |[125|175(7d |}
30 (36 |le |RS (record separator) 62 |76 |3e |> 94 |136|5e |~ ||126|176|7e |~
31 (37 |1f |US (unit separator) 638 77831 RT 95 |137|5f |_ [|127|177|7f |DEL (delete)