Você está na página 1de 31

Comprehensive C++ Tutorial for Beginners - Part 1

Hi there. If you do not know me (you probably do not), my nickname is AzureFenri


r, and this tutorial is *supposed* to teach you the basics of C++. Just promise
not to sue me if it doesn't accomplish its purpose, capiche ?
So you want to learn to program C++? Great! C++ is a powerful language that can
be used to make anything from basic to really advanced multimedia programs. But.
..before you can use such a great tool, you have to know how to use it!
*Insert reader groans here*
Hey, didn't I tell you not to call your lawyer? You didn't? Good boy! That's one
less lawsuit for me today .
Anyway, the basic C++ syntax is still best illustrated by the *trumpet roll* HEL
LO WORLD! program. As banal and clich s it sounds, HELLO WORLD is relatively easy
to dissect and probably easy for a first-time programmer to grasp.
So, open your C++ compiler, and type in the following phrase:
#include <iostream.h>
What does this do? It adds the "bells, whistles, and other stuff" that you need
to type stuff into a DOS window and accept more stuff from the user.
Now, type in the following after the #include line:
int main()
{
cout << "Hi ATARI!";
return 0;
}
That's your basic Hello World program . Don't worry, I'll explain the various pa
rts of the program.
Every C++ program has to have a main function. When you make programs that flash
stuff in DOS windows, this main function, or "subprogram," or code subdivision,
is conveniently named "main." The line:
int main()
Basically tells the compiler that you are defining a function called main. If yo
u do not understand the concept of functions yet, don't worry. I'll explain that
in a later tutorial. For now, just realize that int main() is the code that yel
ls to DOS, "HEY!!! LOOK AT ME!!! I'M MAIN!!! I'M ALL SPECIAL AND 1337 AND WHATNO
T SO RUN MY CODE FIRST!!!"
Now there's a left brace ({), followed by more code, followed by a right brace (
}). So what the heck are those ugly looking things doing there?
Well, the braces { } enclose a "block", or group, of code. The two braces basica
lly group the statements:
cout << "Hi ATARI!\n";
and

return 0;
together into one block of code. This tells main(), "Oh! Everything inside the b
races belongs to me! I'm special and I have all two lines of code!!! Yay!" If yo
u omitted the brackets, like this:
int main()
cout << "Hi ATARI!\n";
return 0;
Then main() will think, "Oh, so I only have one line of code. How sad for me...b
ut wait! There's another line, return 0;, that's sitting out there, and it's not
claimed by anyone else! That's an environmental waste!!! I will throw a flaming
error and refuse to compile! Yeah, that should teach him not to litter code!"
(VOCABULARY: compile: to change a piece of hand-typed code (like C++ code) into
an executable program)
Anyway, the cout means Console Output, or "write stuff on that ugly black DOS wi
ndow." cout << "Hi ATARI\n"; tells DOS to write "Hi ATARI" followed by a LINE FE
ED (basically start a new line). Yes, \n means "Start a new line."
The text that you want to write must be enclosed by double quotes ("). So, if yo
u want to write:
Bart was, is, and always will be my king![ENTER]
You would use:
cout << "Bart was, is, and always will be my king!\n";
Did you notice that semicolon on the end? Every actual line of code must end wit
h the semicolon. The semicolon basically tells the compiler that one line of cod
e has ended and another line is about to begin. However, you DO NOT add a semico
lon after the int main(). Why? If you did, it would mean that the main function
ENDED at the semicolon. But wait! If main ended there, then it couldn't "possess
" the block of code after it, which would mean that the whole block of code was
an environmental waste! Of course, you know how much C++ compilers hate litterin
g code. You do not include a semicolon after ({) and (}) either.
Finally, we have the code:
return 0;
This tells the compiler that the function (and in this case, the program) has en
ded with no errors.
Now that you know how to write stuff on that ugly DOS window, its time to learn
how to ask the user for stuff. As you know, a program would not be very useful i
f it just displayed text continuously...or in computer nerd terms, "All Output a
nd no Input." Thus, if you want to be a good C++ programmer, you MUST learn how
to obtain input from the user.
[AzureFenrir continues in a monotonous voice for hours. Suddenly, a masked GW me
mber barges into the room and bombards AzureFenrir with GW Productions? Multi-Pu
rpose Tar and Feathers. Two days and several baths later, a slightly wet AzureFe
nrir returns unharmed and continues to write this tutorial]

Anyway, to accept user INPUT, you must use another statement, cin, which stands
for Console Input. It's used like this:
cin >> variable;
But wait! What the heck is a variable?! If you've ever used a game maker (like R
M2K), then you have an idea of what variables are. If not, variables basically "
contain" a value that you can modify and retrieve. You an create a variable like
this:
int variablename = 0;
Variablename is the name of the variable. It can be ANYTHING, as long as it cont
ains only letters, numbers, and underscores. Furthermore, variable names cannot
begin with a number. It must start with a letter or underscore.
int tells us that the variable contains an integer, or a whole number. If you wa
nt the variable to store something else, you can substitute int for something el
se, like:
bool
Boolean value. Can only contain 0 and 1. Acts similar to RM2K switches.
char
Can contain ONE ASCII character, like 'a', 'G', '6', or '&'.
int
Can contain a whole number.
long
Can contain a whole number. Can contain numbers too big for int to handle.
float
Can contain a decimal number, like 5.324.
double
Can contain a decimal number. More precise than single.
The zero at the end basically tells the compiler that the variable starts off wi
th the value zero. If this is omitted, then the variable will start off with a r
eally small number (like -2^64).
So, what are variables used for? They are most useful for input and for storing
numbers/letters for future use. They an also be manipulated, like:
int variable1 = 0;
int variable2 = 0;
variable1 = 5;
variable1 = 4 + 7;
variable2 = variable1 + 3;
As you can see, performing arithmetic operations with C++ works the same way as
real-world arithmetic operations. Therefore, if you want to calculate five plus
five, then you can simply use 5 + 5. Similarly, five plus the variable x can be
expressed as 5 + x. The symbols used for multiplication and division are (*) and
(/), respectively. Prentices ( ) may also be used to group operations.
So, back to user input. If you want to ask the user, say, how old is ATARI, you
can use something like:

int ATARIAge;
cout << "What is ATARI's age?\n";
cin >> ATARIAge;
Then, when you run the program, you'll see something like:
What is ATARI's age?
_
(The _ represents the input cursor)
Now, you can also display variables, like:
cout << "X equals " << x << "\n";
Notice how I used three << signs? That is perfectly legal in C++, so if you want
to display two, three, or many different things, you can type:
cout << thing1 << thing2 << ... << thingn;
So, let's modify our Hi ATARI program to include some user input:
#include <iostream.h>
int main()
{
int ATARIAge = 0;
cout << "Hi ATARI!\n";
cout << "What is ATARI's age?\n";
cin >> ATARIAge;
cout << "ATARI's age is " << ATARIAge << "!\n";
return 0;
}
If you run this program, you should get:
Hi ATARI!
What is ATARI's age?
If you typed in an age, you'll get something like:
Hi ATARI!
What is ATARI's age?
13
ATARI's age is 13!
How cool is that? (No offense meant, Mr. ATARI. I just needed an example.)
So...in this tutorial, you should have learned the following:
How
How
How
How

to
to
to
to

build a basic C++ program


write text onto a DOS window
define a variable in C++
prompt the user for data

That's all for now . In the next tutorial (that's right, there's ANOTHER one), I
will discuss more features of C++, including IO control, more arithmetic operat
ors, as well as introduce the concept of boolean operations.
*Insert reader groans/lawsuits/tar and feather here*
Hey! Why are you groaning? You should have known that this is only the first of
a ELEPHANTINE CHAIN of C++ tutorials covering everything from DOS-based C++ to c
onceptual programming to Visual C++ to DDE/OLE to...hopefully, COM+.
I must now disappear before they find me. So...look for my next tutorial and hav
e a nice da---[AzureFenrir is abducted by a group of GW members with black masks]
__________
Part 2
________
Hello, World!
Yep, it's AzureFenrir again. I'm the idiot who forgot to type </I> on a previous
tutorial, resulting in a whole mess of italic text (until a staff member fixed
it). I'll make sure to check this tutoial with frontpage so that THAT doesn't ha
ppen again.
Anyways, here I am with ANOTHER tutorial on C++. This time, I will continue at w
here I left off last time and ingrain more and more and MORE AND MORE...(repeate
d any times)...MORE C++ into your tortured minds. MWAHAHAHAHAHA!
*Insert more user groans and masked GW kidnappings here*
OK, this tutorial assumes that you have (hopefully) learned/know the stuff in my
last tutorial. As promised, I will introduce the concept of I/O manipulation in
this tutorial (it's looooong). However...let us start with a easier concept - c
omments.
Comments are stuff that has no effect on your program. Basically, it does nothin
g. Nada. Noes. So what the heck are these useless code pieces used for?
Well, nothing, to tell you the truth, but they can make your code easier to read
. Since comments does not do anything to your program, you can put anything you
want in a comment. This makes comments ideal for describing code and organizing
stuff.
A comment can be created in two different ways:
// Comment
/* Comment */
So...how to they make code look better? Well, since comments are not included in
your final program, you could use them to organize and describe parts of a prog
ram, like:
int main()
{
// This code defines a variable representing ATARI's age.
int ATARIAge = 0;

cout << "What is ATARI's age?\n"; // Displays a prompt that asks for ATARI's age
cin >> ATARIAge; // Asks the user for ATARI's age
return 0; // No errors, program end
}
Comments may seem somewhat trivial - I mean, we can tell what the ATARI's age pr
ogram does just by glancing at it. However, keep in mind that when you write lar
ge programs with extremely lengthy subroutines and coding, comments will serious
ly help you find the code that you're looking for in an assorted junkyard of stu
ff.
I love the word "stuff"...but that is beside the point.
In the last tutorial, we talked about "writing stuff to that ugly DOS window." H
owever, C++ will not be very useful for game programming if the you could only t
ype stuff line-by-line, character-by-character, with no way to manipulate it wha
tsoever. So, how do we manipulate text?
Well, before you do any manipulating, you must add another odd # line to your co
de:
#include <iomanip.h>
Yep, another line with that silly #include symbol. Remember from my last tutoria
l that #include <iostream.h> adds the bells, whistles, and "stuff" that you need
for writing and reading text? Well, #include <iomanip.h> adds the "stuff" that
you need for manipulating text.
Now, let us look at how we can manipulate output.
Creating Fixed-Width Output using setw
The C++ setw function allows you to set the "text width" for the next item that
is being displayed. This is especially useful if you are displaying tables and d
ata grids.
So...how do you use it? You have to stick it in the cout function, like:
cout << setw(n) ...
This would print the next "stuff" with a fixed width of 5.
Here's an example:
cout << setw(8) << "Hello!" << setw(12) << "Bonjour!" << setw(10) << "Buenos Dia
s!\n";
This yields the result:
Hello! Bonjour!Buenos Dias!
Note that the last entry, "Buenos Dias!", is 12 characters long. However, we onl
y gave it a width of 10! Because the number of characters in the printed "stuff"
is larger than the number of characters it is allowed, it overflows the space,
making setw useless.

Formatting Output Using setiosflags and resetiosflags


The C++ setiosflags function allows you to set certain output "flags". Unlike se
tw, flags set with setiosflags will continue to affect the "Stuff" that you writ
e to DOS until it is removed. You can remove flags with resetiosflags.
For example:
cout << setiosflags(ios::hex) << 255 << resetiosflags(ios::hex);
This will print "FF", which is the hexadecimal equivalent of 255. The resetiosfl
ags command then removes the ios::hex flag so no subsequent outputs are affected
.
Here's a list of many useful flags that you can use with setiosflags:
ios:ct
Displays integers as base-8 octagonal numbers.
ios::dec
Displays integers as normal decimal numbers.
ios::left
When setw is used, aligns text to the left.
ios::right
When setw is used, aligns text to the right.
ios::fixed
Shows decimal numbers in a fixed decimal format with no scientific notation.
ios::scientific
Shows decimal numbers in scientific notation (e.g. 3.57e-10)
ios::showpos
Shows a positive sign on positive numbers (e.g. +253)
ios::showpoint
Always show the decimal point. This will usually result in numbers like 354.000.
Do not forget to use resetiosflags to undo any flags that you use - they will af
fect all subsequent outputs!
Displaying Fixed Values Using setprecision
The C++ setprecision function, when used in conjunction with setiosflags(ios::fi
xed), can display FIXED NUMBERS, or numbers to a certain decimal point. For exam
ple:
cout << "You have $" << setiosflags(ios::fixed) << setprecision(2) << 25.5 << ".
\n";
This will display:
You have $25.50.
setprecision sets the number of digits following the decimal point when used wit
h ios::fixed (or ios::scientific). When none of these two flags are set, setprec

ision specifies the "total number of significant digits in a number." Don't worr
y about this, as you'll probably never use it anyway.
setprecision, like setiosflags, will continue to affect every number that you di
splay using cout. To reset the precision, just type setprecision(6), which is us
ually the C++ default.
Having fun with setw using setfill
Whenever you use setw to set I/O width, the unused areas always contain ugly spa
ces. Well, the good news is...that can be changed by using a function names setf
ill!
setfill is used like this:
cout << setfill('?') << setw(n) << Stuff << "\n";
Where ? is the character that you want to use for setw.
Did you notice the single quotes around the setfill? There's a reason for that.
Double quotes "" will designate a string, or more than one character. Single quo
tes designate ONLY ONE CHARACTER. Of course, setfill can only fill enpty spaces
with characters (it's one of C++'s limitations), so you must use single quotes.
Example time!!! Yay!!!
cout << "Xanqui's Autobiography" << setfill('.') << setw(20) << 3 <, "\n";
Will result in:
Xanqui's Autobiography...................3

Now that you've finished reading that horribly long tutorial on output manipulat
ion, relax and stretch your legs! Take a break and eat some mangos...for there's
another section coming up.
Done? Not yet? I'll wait.
Done? OK, let's move on (but make sure to share the mangos with the class!).
Now comes input manipulation. Before I introduce input manip, I want to first el
aborate on the concept of strings.
As you know from my previous tutorial, C++'s char operator stores one character.
But what if you want to store more than one character...or heck...even a whole
paragraph?
Well, you can do so like this:
char stringname[n] = "Initial String";
n is the total number of characters that your string can store, minus one. Thus,
if you want your string to store ten characters, then n must be 11 (char string
name[11]).
Are you wondering why? Well...I won't tell you why, unless if you share those ma
ngos with me.

What? I'll be fired if I don't reveal the secret? OK...fine...every C++ string e
nds with a special letter called a NULL character ('\0'). This null character is
never displayed, but is still there. Why is this NULL character there? It tells
C++ that the string has ended, and it shouldn't display any more characters. If
the null character is not present, then C++ will continue to read more and more
characters, and may eventually intrude upon memory space occupied by other stuf
f from other programs. Those programs won't like C++'s intrusion and may crash.
Although this usually doesn't happen (since C++ will usually encounter another N
ULL character before it intrtudes upon those spaces), it will still print a bunc
h of strange and unsightly junk after your strings.
Unfortunately, you cannot set strings by just using something like stringname="x
xx". You have to use C++'s string functions, the most commonly used ones being s
trcpy, strcat, and strlen.
Before you use these functions, you must add another silly little #include state
ment:
#include <string.h>
strcpy is used to set strings to specific values. It is used like:
strcpy(stringname, "String that you want to set stringname to");
strcat is used to add things to the end of strings. For example, if string1 cont
ains "Hi", then:
strcat(string1, "Hello");
will change string1 to:
"HiHello"
strlen finds the actual length of strings. It is used like:
variable = strlen(stringname);
For example:
cout << strlen("Hi") << "\n";
Will return 2, since Hi is two characters long.
You can use in to get the user to enter a string, like:
cout << "Please enter a string:\n";
cin >> stringname;
This will ask the user to enter a string, and then store the first word that the
user enters in the string stringname.
Oo, now we have a problem. What if we want the user to enter a whole sentence? T
hat could be solved by the cin.get function, which is used like this:
cin.get(stringname, n, '\n');
stringname designates the name of the string that you want to write to. n is the
number of characters that you want to be stored, and '\n' MUST be in single quo
tes (because it must designate a character). OF course, the character limitation
is not much of a problem, since your string is limited to x number of character
s anyway.
So...if we use cin.get, what happens if *gasp* the user types more than n charac
ters of stuff?
Well, C++ will remember the extra stuff and will use it on the next cin statemen
t. Because there is already stuff for it to use, cin will NOT ask the user for i

nformation, which will probably mess up your prompt, like:


Please type 3 characters: 3425423462
Please type 4 characters:Please type 2 characters:Please type a number:What is y
our name? _
That doesn't look good, does it?
So how do we fix it? Well, C++ provides ANOTHER statement, cin.ignore, that will
obliterate those stored waste and send it to another dimension!!!
cin.ignore(30000, '\n');
This tells C++ to ignore the next 30000 characters in its storage, which would e
mpty the C++ storage room. This would force C++ to ask to user for more informat
ion, thus fixing the messy prompt problem.

Phew...that about wraps it up for input/output manipulation. Now, let's discuss


a few more C++ operators before I retire and begin playing Naufragar Crimson.
% operator:
The % operator takes the modulus of two values (i.e. the remainder). For example
, 5 % 2 = 1 because 5 / 2 has a remainder of 1.
+=, -=, *=, /=, %= operators:
These operators does that specified operation on the variable, and stores it in
the value. For example, x += 3 will add three to x and store the result in x. it
is the same as x = x + 3.

So...that's all I'll discuss on this tutorial...I'll teach you how to use C++'s
"FORK statements and LOOP statements" in the nenxt tutorial...
READER: Hey! You promised us that you will show us boolean stuff!
AzureFenrir: Um...yeah, but I/O Manipulations is longer than I expected...and bo
olean stuff fits better in my next tutorial anyway.
READER: What?!
AzureFenrir: Naugragar: Crimson is practically calling out my name...and I don't
feel like writing more. So...hey, point that pulse gun somewhere else, OK? Wait
...don't...YAAAAAAAAAAA
_________
Part 3
_________
Comprehensive C++ Tutorial for Beginners - Part 3
Well, well, the series continues . AzureFenrir isn't a lazy bastard after all...
listen to Azure referring to himself in third-person!
Oops, looks like I just digressed.
This tutorial, the third of the series, will enlighten you with grand knowledge

of boolean operations and selection structures. So...pack your thinking caps and
prepare for programming Nirvana!
The concept of Boolean variables is easy. Boolean deals with two variables: 0 an
d 1, false and true. 0 means false, and 1 is true. This is very similar to how t
he computer makes decisions - yes and no, do one thing or do the other. Boolean
values are commonly used through one of these six operators:
a == b
Returns a value of true (1) if a and b are equal. Returns false (0) otherwise.
[NOTE: This is not the same as the assignment (=) operator. To make comparisons,
you MUST type two equal signs, not one!]
a != b
Returns a value of true (1) if a and b are NOT equal. Returns false (0) otherwis
e.
a > b
Returns a value of true (1) if a is larger than b. Returns false (0) otherwise.
a < b
Returns a value of true (1) if a is smaller than b. Returns false (0) otherwise.
a >= b
Returns a value of true (1) if a is larger than or equal to b. Returns false (0)
otherwise.
a <= b
Returns a value of true (1) if a is smaller than or equal to b. Returns false (0
) otherwise.
So...what the heck does that mean? Let us use an example to demonstrate:
bool temp;
temp = (3 > 5);
Remember bool variables from Part 1 of this tutorial? This code will store the v
alue false (0) in temp, because 3 is not larger than five!!! (Well, maybe in oth
er planets/dimensions, but we're talking about earth, our dimension).
However,
temp = (7 > 5);
Will store true (1) in temp, because 7 IS greater than five. How fun was that?
READER: Zzzzzzzzzzzzzzzzzz
Anyway, (Wake Up!) Boolean structures are used in many different ways in C++. In
this tutorial, we will discuss the selection structures - basically, the if str
uctures, the else structure, the switch structure, and the break statement. Don'
t worry, this is a beginners' tutorial, which means I'll walk you through these
statements step-by-step.
The "if" Structure
The if structure is analogous to RM2K's FORK statements. Basically, it allows yo

u to run a piece of code if it's conditions are met - that is, if it's inner cod
e returns true (1).
You can use it like this:
if(condition)
{
Insert what happens if the conditions are met here
}
Here's an example:
#include <iostream.h>
int main()
{
int ATARIAge = 0;
// Again, no offense meant to ATARI
cout << "ATARI's Age: ";
cin >> ATARIAge;
if(ATARIAge < 18)
{
cout << "ATARI is younger than 18!\n";
cout << "ATARI is young!\n";
}
}
When you run the program, you'll get something like:
ATARI's Age: _
Type in something smaller than 18 and watch the text appear! 'Tis magic, I tell
ya, magic!!!
*Insert groans here*
Did you notice the braces { } that's just below the if statement? It looks just
like the braces under the main function! Well, if you read my first tutorial (or
if you know a lot of C++ and are reading this tutorial just for fun), then you
know that the braces signals to main that all of the code under it belongs to it
. The braces under the if statements serve the same purpose - they tell the if s
tatement that it has exclusive control over everything inside the braces! That p
ower-hungry bastard...
What happens if you omit the brackets, like this:
if(ATARIAge < 18)
cout << "ATARI is younger than 18!\n";
cout << "ATARI is young!\n";
Well, there's no run-time errors, and if you run this code and type in something
smaller than 18, then it works regularly. However, run it again and type a larg
e value (like 34)...oh no! The program still displayed:
ATARI is young!
When you removed the braces, only the first line of code, cout << "ATARI is youn

ger than 18!\n";, belonged to the if statement. Since the if statement cannot co
ntrol the second line, the second message will display, regardless of what you t
ype.
So...just remember to always include braces, capiche?
If you've ever used RM2K (or any other scripting/programming language), you shou
ld be familiar with the concept of "else" statements. If you don't, well...they
appear right after an if statement, and contains "stuff" that will run if the co
ndition in the if statement is NOT met.
MWAHAHAHAHAHAHA!!! WHEN I PERFECT MY POWERFUL MUTANT ARMY, THE WHOLE WORLD IS MI
NE!
That proves that I belong in an asylum...anyway, the else statement MUST immedia
tely follow the end brace } of an if statement. There cannot be ANYTHING (except
comments [and some compiler directives]) between the if } and the else statemen
t!!!
Here's an example of an else statement:
#include <iostream.h>
int main()
{
int ATARIAge = 0;
// Again, no offense meant to ATARI
cout << "ATARI's Age: ";
cin >> ATARIAge;
if(ATARIAge < 18)
{
cout << "ATARI is
cout << "ATARI is
} else {
cout << "ATARI is
cout << "ATARI is
}
}

younger than 18!\n";


young!\n";
either older than or exactly 18!\n";
experienced!\n";

I don't need to know ATARI's real age, so even if you know it, don't post it, ca
piche?
You an also have multiple if branches by using else if:
#include <iostream.h>
int main()
{
int ATARIAge = 0;
// Again, no offense meant to ATARI
cout << "ATARI's Age: ";
cin >> ATARIAge;
if(ATARIAge < 18)
{
cout << "ATARI is younger than 18!\n";
cout << "ATARI is young!\n";

} else if (ATARIAge <= 56) {


cout << "ATARI is between 18 and 56!\n";
cout << "ATARI is cool!\n";
} else {
cout << "ATARI is older than 56!\n";
cout << "ATARI is experienced!\n";
}
}
(Technical stuff: else if is not really a single C++ keyword. Rather, it's a com
bination of two keywords - if and else.)
Do you understand all this so far? Yes? Good! Now, I'll show you a few new boole
an operators before ending the tutorial with the "switch" statement:
a && b (Boolean AND operator)
Returns true (1) if both a and b are true (1). Returns false (0) otherwise.
a || b (Boolean OR operator)
Returns true (1) if either a and b are true (1). Returns false (0) if neither ar
e true.
!a (Boolean NOT operator)
Returns true (1) if a is false (0). Returns false (0) if a is true (1).
Basically, returns the opposite of a.
How do you use these? Elementary, my dear reader. a and b represent different ex
pressions. For example:
(2 > 5) && (3 < 4)
Returns false (0). Although 3 is less than 4, 2 is NOT greater than 5. Because t
he && operator requires both sides to be true (1), it returns false (0). However
:
(2 > 5) || (3 < 4)
Returns true (1). 3 is less than four, and because the || operator only requires
one side to be true, this expression returns true (1).
Hopefully, those are easy concepts for you to grasp. Now, before I end this tuto
rial, I want to quickly talk about one more C++ selection structure, the switch
keyword. The switch keyword is a unique selection structure. It accepts a variab
le instead of a boolean statement, and has multiple branches depending on what t
he variable contains. For example:
switch(variable)
{
case 1:
somecode
break;
case 2:
someothercode
break;
case 3:
somemorecode
break;
default:

defaultcode
}
If variable is equal to one, then the statement will run somecode. If it's equal
to two, then the statement will run someothercode. If it's equal to three, then
somemorecode will run, and if variable is anything else...well...then defaultco
de will run.
Hopefully, this tutorial aided you in your quest to learn the great language of
C++. If you really like this tutorial, please attempt to convince GW that kidnap
ping AzureFenrir is not recommended, and that MY TUTORIALS SHOULD BE REVERED BY.
..THE WORLD! MWAHAHAHAHAHAHAHAHA!!! GLOBAL DOMINATION!!!
[AzureFenrir is assassinated by masked GW members with Kotetsus]
________
Part 4
________
Comprehensive C++ Tutorial for Beginners - Part 4
Guess what? I'm back with more C++ tutorials!
*AzureFenrir is immediately shot*
Hey, wait, wait. If you kill me, then I can't write any more C++ tutorials! You
don't want that, do you?
*AzureFenrir is immediately shot several times with a chain gun*
OK, OK, I'll start the actual tutorial now. Just don't shoot me anymore and put
the guns down...that's right, I can't file suit if I'm dead, can I :P?
Anyway, this tutorial shall educate you on the amazing subject of C++ loops. If
you've never programmed before, loops allow you to repeat certain commands, with
slight modifications, until a certain conditions are met. For example, a loop m
ay cause the program to display "Hello!" 100 times, or slap someone until they t
ype "I surrender" with their nose while raising a white flag...never mind.
Basically, just remember that loops allow you to repeat pieces of code over and
over again.
"For" Loops
"For" loops are the first types of loops that we will see. Like all loops, they
allow you to repeat a block of code until a condition is met. The syntax of "for
" loops (basically, how you use it) is as follows:
for(initialization; condition, increment)
{
Code that you want to repeat;
}
Whoa! Did you understand what the heck that meant? Well, first of all, you know
that loops allow you to repeat code, so the Code that you want to repeat is basi
cally whatever code that you want to repeat. Let's focus our attention on the th
ree parts of the "for" loop, the initialization, condition, and increment statem
ents.

The initialization statement runs at the very begining


epetition of the blocked code occus. In fact, the code
he code that you want to repeat is executed ONCE! This
initialize a variable (like i) to a number so that it
of the loop.

of the loop, before any r


in here will run before t
code is basically used to
could be used in the rest

The condition statement will end the repetition if it's false. For example, if t
he condition is, say, i < 11, then whenever i is larger than or equal to 11 (whi
ch would make the statement FALSE), the loop will terminate.
The increment statement will run every time the loop interates, or repeats. So,
if the statement contains, say, i++, then every time the code in the loop runs,
i increases by one.

Still confused? Don't worry, I'll walk you through this sample for loop step-bystep, using diagrams to show you the actual process of the code. So, for the fol
lowing sample code, let's assume that the variable i has already been declared:
for(i = 2; i < 5; i++)
{
cout << "The variable i is currently " << i << '\n';
}
return 0;
Let's walk through this code, using bold to show the code that is currently bein
g run. When we begin, the C++ compiler reads the for statement:
for(i = 2, i < 5; i++)
Because the loop just started, we must run the initialization code first, so:
for(i = 2; i < 5; i++)
Now, i has been initialized to 2. Now, the code goes to the conditional statemen
t and calculates its value:
for(i = 2; i < 5; i++)
i = 2
Since the conditional code (i < 5) has not yet been reached (since i = 2, and 2
is smaller than 5), we must start our first run through the loop, so we run the
cout code:
cout << "The variable i is currently " << i << '\n';
i = 2
This writes the words "The variable i is currently 2" to the console. Finally, w
e encountered the (}) code, which indicates the end of the for block. Because lo
ops repeat code, the program now leaps back to the for code:
for(i = 2, i < 5; i++)
i = 2
Because this is the SECOND time through the loop, the initialization statement (
i = 2) doesn't run. Instead, the increment statement runs:
for(i = 2, i < 5, i++)
i = 2

After this code, i will now equal 3. The condition statement will run again:
for(i = 2; i < 5; i++)
i = 3
Now, because three is STILL smaller than 5 (the condition statement is still tru
e), the code inside the for loop runs again:
cout << "The variable i is currently " << i << '\n';
i = 3
This writes the words "The variable i is currently 3" to the console. This code
then runs again, in the same way:
for(i = 2, i < 5, i++)
i = 3
for(i = 2; i < 5; i++)
i = 4
cout << "The variable i is currently " << i << '\n';
i = 4
Now, the words "The variable i is currently 4" will be written. Finally, let's r
un through the final interation of the loop:
for(i = 2, i < 5, i++)
i = 4
This would make i equal to 5. Now, the condition statement is NO LONGER reached:
for(i = 2; i < 5; i++)
i = 5
Obviously, five is not smaller than 5, so the condition statement (i < 5) will r
eturn false. This causes the for loop to skip its code block (and thus not run t
he cout statement) and run the next statement:
return 0;
Now, the program exits, and leaves the following output:
The variable i is currently 2
The variable i is currently 3
The variable i is currently 4
Capiche?

Now that you undestand the basics of for loops, let's look at what else for loop
s can do. Obviously, the above loop type (which is the most common use for "for"
loops) runs the blocked code a finite amount of times depending on the starting
and ending values of i.
However, because the "statements" can consist of any code, you can make "for" lo
ops such as:
for(char string[25] = ""; strlen(string) < 15; strcat(string, "a"))

or:
for(int i = 0; abs(i) < 8; i = (i * j) + k - m)
As you can see, you can use other commands (such as int i = 0 and functions (as
well as ANY valid C++ statement) in for loops. In fact, you can even have multip
le initial and increment statements:
for(int i = 0, int j = 0; i + j < 10; i++, j++)
As you can see, you can use commas (,) to use multiple commands for a statement.
In the above example, the initialization statement initialized BOTH i and j to
0, and the increment statements adds one to BOTH i and j. Thus, two variables we
re used to evaluate and terminate the "for" loop.
Remember that variables used in the "for" loop are in no way sacred or protected
. Therefore, you can change them anywhere in the for loop. In fact, you can even
change the variable so that the for loop terminates early:
for(int i = 0; i < 8; i++)
{
i = 12;
}
This code will cause the for loop to run once and immediately end. After all, on
the second time through the for loop:
for(int i = 0; i < 8; i++)
i = 12, which caused the condition statement to return false (0). This causes th
e for loop to end, even though an external code set the i statement to 12.
You can also eliminate certain parameters of the for loop, like:
for(int i = 0; i < 8; )
Or even:
for( ; ; )
The above statement will create a phenomenon called an infinite loop, which is a
loop that will never end because its condition does not exist or never will be
met. Infinite loops are usually poor coding practices since they make your progr
am run forever. If you've ever seen windows crash, and nothing seems to be worki
ng (not even Ctrl-Alt-Delete) - well, that's probably an infinite loop.
Finally, you can also have multiple conditions for the conditional statement, bu
t the process is a bit different:
for(int i = 0; (i < 3) && (i > -5); i = i * j)
You have to use boolean operators to link the two conditions. After all, C++ doe
sn't care what code you put in the conditional statement, as long as it gets eit
her a true or a false value. If it gets something else (like a dereferenced stri
ng), then it will start raging.
Remember that any C++ statement can be empty, so the for loop doesn't even need
to contai any code. For example:

for(int i = 0; i < 10000; i++) ;


These types of code are usually used to delay the program for a moment, although
it does have other uses.

While Loops
Phew! That lesson on the "for" loop is certainly very long, isn't it?
Well, you'll be glad to learn that "while" loops are simpler. Its syntax is:
while(condition)
{
Code that you want to repeat;
}
"While" loops repeat the Code that you want to repeat until the condition statem
ent returns false. So, if condition is i < 6, then the code repeats until i is N
O LONGER smaller than 6. Similarily, if the condition contains i == 7, then the
loop will repeat until i does equal seve. Basically..."while" loops are essentia
lly the same as for loops with no initialization or increment. In fact, it could
easily be written as a for loop, like this:
for( ; condition; )
Here's an example of a "while" loop in action:
while(getch() != '\r')
{
cout << "You will press enter or else!!!\n";
}
So, what does this program do? Well, obviously, we haven't learned the _getch()
function yet, so let's briefly cover that before continuing.
getch is a very unique little function that allows us to read ONE CHARACTER from
the console without forcing the user to type "ENTER" (somewhat to "Press Any Ke
y to Continue"). Therefore, this code basically displays "You will press enter o
r else!!!" until the user actually presses enter. It's quite similar to another
function, cin.get(), except cin.get() requires you to press after typing the cha
racter.
So...we don't really need to walk through this. The code simply keeps running th
rough the code until it encounters a '\r' character, which indicates that is pre
ssed.
Oh, and you probably have no idea what '\r' is, and why we are not using the new
line '\n'. Well...there are two characters returned when is pressed: a carriage
return, and a line feed. Normally, in the older days, carriage return ('\r') is
supposed to return the cursor to the beginning of the line, and line feed ('\n')
is supposed to move it to the next line. We've only used '\n' because DOS will
recognize it as a newline character even if it's not accompanied by a '\r'. Howe
ver, for compatibility purposes, the key will retun BOTH the '\r' and '\n' chara
cters, and since getch() only gets the first character typed in, it will retun '
\r' and discard '\n'.
Did you understand that? If not, just remember that will result in both '\r' and
'\n', and getch will thus only return '\r'. The cin class, however, will proper

ly handle this \r so you won't have to worry about it.

Do...While Loops
"Do...While" loops are exactly the same as "While" loops...except for one major
difference:
do
{
Code that you want to repeat;
} while(condition);
Did you notice that the "while" is on the very bottom? That's because, unlike "w
hile" loops, "Do...While" loops check the condition at the very bottom of the co
de, which means that the code inside the loop will be guaranteed to run at least
once.
What does this mean? Well, let's look at an example:
int i = 8;
while (i < 5)
{
cout << "Here is looped code!\n";
}
This code will not do anything (well, actually, it will create a new variable an
d set it to 8, but it will not PRINT anything). Why is that? Well, when the syst
em reaches the while (i < 5), it checks the condition and finds it to be FALSE (
8 is not smaller than 5). Therefore, the loop exits immediately, and the cout co
de is never run.
But what about this:
int i = 8;
do
{
cout << "Here is looped code!\n";
} while (i < 5);
In this case, because the while (i < 5) is behind the code, the "cout" code will
run once before the compiler realizes that i is not smaller than 5. This makes
the code print "Here is looped code!" once.

Exiting Loops Early


There is another way to exit loops, even if the conditions are not met. This is
accomplished with the break keyword:
break;
What a simple keyword! It doesn't even need any parameters . Simple, happy, joyo
us...ahh...
*snap*

Oh wait, where was I? Right. The break statement unconditionally exits out of th
e current loop (even if the condition is not met). So:
while(true)
{
cout << "Here is looped code!\n";
break;
cout << "Here is more looped code!\n";
}
This code will only print "Here is looped code!" When the interpretor reaches th
e break statement, it will immediately exit the loop, even though the loop is in
finite (the condition statement is always true, and "while" loops will only end
if the condition is false).

Going to the Next Iteration of a Loops Early


What does "iteration" mean? Well, it's basically one "run" of the loop. So, when
the code finishes its code and begins to repeat it, it's starting a new iterati
on.
So, for this infinite loop:
while(true)
{
cout << "Here is looped code!\n";
}
Every time the "Here is looped code" is displayed, the interpretor returns to th
e "while" statement, and another iteration is begin. To top it off, continue is
used as simply as break:
continue;
Again, what a simple keyword! It doesn't even need any parameters . So...we need
an example to complicate this simple statement:
for(int
{






}

i = 0; i < 10; i++)


cout <<
if((i %
{

}
cout <<

"The number is " << i << '\n';


4) != 0)
continue;
"It is not a multiple of 4!\n";

This results in:


The number is 1
It is not a multiple of 4!
The number is 2
It is not a multiple of 4!
The number is 3
It is not a multiple of 4!
The number is 4
The number is 5

It is not a multiple
The number is 6
It is not a multiple
The number is 7
It is not a multiple
The number is 8
The number is 9
It is not a multiple
The number is 10
It is not a multiple

of 4!
of 4!
of 4!
of 4!
of 4!

This code will only print "It is not a multiple of 4!" if i is not a multiple of
4. If i is, then the interpretor will run the "continue" statemeny and immediat
ely go to the next iteration of the loop, completely ignoring the rest of the co
de (which is the cout << "It is not a multiple of 4!\n"; statement).

A look at ancient C++: Labels and Goto Statements


Dn7 always accuses me of including old C++ statements in my tutorials (which I m
ust admit to - sometimes, I am still nostaglic about certain old C++ material).
So, to end this tutorial, I want to give you a taste of one of the most ancient
loops available: Labels and GOTO Statements.
GOTO has been widely used in older programming languages, starting (as far as I
know) in ALGOR. Presently, it is shunned by many programmers (including me) beca
use of unstability reasons - most programmers believe that jumping around in cod
e makes it disorganized and makes debugging difficult. Although it is generally
replaced by loops, it can still be used in your program. No one will know if you
used a GOTO statement unless if they look through your entire program in assemb
ly.
You can define a label with a colon, like:
label_name:
And return to a certain label using:
goto label_name;
GOTO will return the interpreter to the label label_name, so:
superlabel:
cout << "INFINITE LOOP\n";
goto superlabel;
Will cause an infinite loop. GOTO statements are thus usually used in if stateme
nts or other conditional functions.

All right. This tutorial is a good way to end a good Saturday. I am AzureFenrir,
and this is a GW Tutorial. Good-bye.
(As you can see, I wrote this conclusion while I was watching the 5:00 news.)
_________

Part 5
_________
Comprehensive C++ Tutorial for Beginners - Part 5
Well, well, we're at five already, aren't we? It's just one more tutorial (Intro
duction to OOP) until the end of this series! This tutorial will simply cover so
me other necessary stuff in C++, such as basic data structures and functions. I'
ll also add a bit of basic C++ file input .
So...since I like old-fashioned C++ (and Dn7 continuously criticizes me because
of it), I will start off by showing you how to use the newer ANSI headers and th
eir more advanced string class.

A Look at a More Modern C++: ANSI Headers and strings


Now, remember how I've always told you to initialize headers like this:
#include <headername.h>
#include <headername2.h>
#include <headername3.h>
// ...
Well, the more modern version of C++ uses another set of headers (called the ANS
I headers), which supports quite a few more modern functions to make your progra
mming life easier. Instead of the above declaration, you should use:
#include <headername>
#include <headername2>
#include <headername3>
// ...
using namespace std;
Whoa! What is this "using namespace std" thing? Well, to ensure that their funct
ions do not somehow conflict with yours due to an identical name, all ANSI funct
ions and classes are encased in a namespace, which serves to keep them apart fro
m your functions (by keeping them in a different area). The command "using names
pace std" simply tells C++ that your program will use the namespace "std" and wi
ll not conflict with any of its functions.
So...what if you do not put this statement on top of your .cpp file? Well, in th
is case, all of the ANSI classes will still remain in the "std" namespace, and y
ou will have to do this to refer to...say...the cout function:
std::cout << "Hello, Gaming World!\n";
BTW, the "\n" at the end refers to the "Line Feed" character. This character wil
l cause an effect similar to endl in DOS (basically, it will start a new line).
Now, you are probably wondering why we need to use the ANSI headers instead of t
he regular ".h" headers. Well, in addition to being the newest C++ trend, the AN
SI headers also offer a lot of things that the standard headers doesn't...and al
l of them designed to make your life much easier than C++'s normal living hell.
Let's use strings to set an example. Do you remember declaring old C-style strin
gs from the second part of my tutorial? Well, it's quite a hassle to keep track
of pointers and string sizes, and the string operations are sometimes quite anno

ying. I know I used to HATE the pointer and string errors that came from charact
er manipulation and dynamic string arrays.
So...what does the ANSI headers offer that will solve this problem? Well, how ab
out a string class?
The ANSI string class is quite easy to use. It can be declared like this:
string NewString;
So...why is this string so much more advantageous? Well, for one, forget about t
he strcpy function. Instead, just set the string directly with the equal opeator
:
NewString = "Hello, Gaming World!";
And what about the strcat function that adds a string to the end of another if t
here's room? Why do we need that when we can simply use +=, without needing to c
heck whether the string goes out of the allotted buffer size?
NewString += " Hello, Bartek Gnaido!";
Not to mention that you could still access individual characters:
NewString[1] = 'u';
The string class also offers a *c_str function that returns a constant string, w
hich is quite handy for certain C and older C++ functions (as well as anything t
hat requires a old school string):
cout << NewString.c_str() << endl;
This class also offers a slew of other useful functions such as find(), replace(
), and insert(), but for the sake of a short introduction to ANSI, I won't descr
ibe them here.

Old School Data Structures: Structs and Unions


How ironic? Right after I show you how to use the newer ANSI headers, I revert r
ight back to old-school structures.
So what are structs and unions? Well, they are custom data types that you, the u
ser, can create. Both of these data structures can contain multiple submembers o
f data, allowing you to easily declare many variables with one declaration.
We'll start with structs. The basic declaration for structs is as follows:
struct MyStruct {
int member1;
double member2;
char member3;
string member4;
}
The members are the variables that the struct "contains." Your program can use a
ny or all of these variables once he declares a new variable with this new data
type:

MyStruct MyNewVariable;
Now, you can access MyNewVaiable's members by doing something like this:
MyNewVaiable.member1 = 3;
MyNewVaiable.member3 = 'u';
if (MyNewVaiable.member2 == 3.251)
{
MyNewVaiable.member4 == "Hello, Gaming World!";
}
So what did we do here? Well, when we declared that MyNewVariable has a MyStruct
data type, C++ automatically created a clean copy of all of MyStruct's members
and gave them to MyNewVariable. Therefore, MyNewVariable now contains an integer
, a double, a character, and a string.
If you declared another MyStruct-type variable:
MyStruct MyNewVariable2;
It will also have a clean copy of all of the structure's members. Therefore, set
ting, say, the member2 member of MyNewVariable will do nothing to the member2 me
mber of MyNewVariable2, and vice versa. They are independent variables, and chan
ges to one doesn't affect the other at all.
Unions are just like structs: they have member variables, and all of them could
be accessed. However, unions store their member functions in the same place, whi
ch means that changing one of the members would change all of the other members,
as well. For example, let's look at the following union:
union MyUnion {
int member1;
char member2;
}
Let's assume that you declare a new variable of this type and set the new variab
le's member1 to, say, 1280:
MyUnion MyNewVariable;
MyNewVariable.member1 = 1280;
Next, let's set this function's member2 to...say...'d':
MyNewVariable.member2 = 'd';
Then, let's output the value of member1 to the console:
cout << MyNewVariable..member1 << endl;
Ho! What is this? MyNewVariable's member1 has changed! Well, unions store all of
its members in the same memory space, which means that member1 shares a memory
space with member2. Therefore, changing the char member will also change a porti
on of the integer member.
Unions are mostly used for multivariable compatibility in the old C days, but ca
n also be combined with structs for a neat trick:
union MyUnion {
long member1;

struct MyStruct {
char byte1;
char byte2;
char byte3;
char byte4;
} member2;
}
Now, you can store a long number in member1, and use member2 to access the indiv
idual bytes in member1. Neat, eh? :P

Functions in C++
Do you remember how every C++ program should start with the function "main"?
int main()
{
// Code here, Blah Blah
return 0;
}
Did you know that this mysterious "main" is actually a C++ function? Well, C++ f
unctions are declared in a similar fashion:
return_type function_name()
{
// Code here, Blah Blah
return return_value;
}
Was that very confusing? Well, let's make a simple function that calculates the
value of 3 + 4 to demonstrate:
long add()
{
return (3 + 4);
}
Do you understand now? The return_type specifies what the function will return (
like string, long, char, double, etc.), and the function_name specifies the name
of the function. You can insert your function's code in the code here part, and
use the "return" keyword to return a value.
To use C++ functions, you must call them, like this:
MyVariable = add();
The above code will assign the value 7 (since 3 + 4 = 7 on Earth) to MyVariable.
But wait...a function would be petty useless if the user can't specify anything,
right? So, let's expand our previous simplified definition of functions to incl
ude these parameters:
return_type function_name(type argument1, type argument2, ...)
{
// Code here, Blah Blah
return return_value;

}
There. The arguments are basically
your function to specify something
, the interest rate of investment,
function more useful by making it

custom "variables" that the user can pass to


(such as the two numbers that should be added
etc.) With this in mind, let's make the above
add ANY two numbers that the user wants:

long add(long a, long b)


{
return (a + b);
}
Now the user can add any two numbers that he/she wants. For example, let's assum
e that you want to add 4 and 5 together and store the result in MyVariable. You
would then use:
MyVariable = add(4, 5);
That's quite easy to understand, right? Remember that a function can have as man
y lines of code as you want - it doesn't always have to be just one "return" sta
tement.
Finally, you can make a function return NOTHING (useful for functions that perfo
rm tasks instead of calculations) by making "void" the return_type:
void function_name(type argument1, type argument2, ...)
{
// Code here, Blah Blah
return;
}
Obviously, in this case, you can't return a value. As a result, you could simply
use "return" by itself to exit the function and return to main (or the calling
routine).
BTW: Functions are usually placed on the bottom of your CPP file, right after fu
nction main(). Because they are usually placed under main(), the compiler will c
ompile these functions after compiling main, and you may get an error when the c
ompiler reaches a reference to your function.
If you didn't understand the above statement, that is OK. Just remember that fun
ctions usually go after main, and function prototypes are usually needed for fun
ctions to work...wait a minute. What is a function prototype?
Well, it's basically a version of the function without any code, like this:
return_type function_name(type argument1, type argument2, ...);
Everything in the prototype
pt for the fact that it has
totype will ensure that C++
onfusing looking for it and

must be the exact same as your actual function, exce


no coding and is terminated by a semicolon. This pro
will know that your function exists, and won't get c
throw out an error.

Oh, and these prototypes goes before the main function.

An Introduction to File Input and Output


You probably know what files are, and if you don't...well, it's a clunk of data

stored in your computer. For example, every Word Document is a file, and so is e
very program, every spreadsheet, every e-mail, every web page, every DrFunk 60-S
econd Paint Picture , and...well, you get the picture.
Let's start with the headers. Obviously, file input/output requires its own head
er, called "fstream":
#include <fstream.h>
Or, if you like, the ANSI version:
#include <fstream>
using namespace std;
Now, after that #include is there, we need the actual code for file input/output
. So, to do that, we need to declare a new fstream object:
fstream file;
So...what is this fstream class? Well, it gives us all the functions and operato
rs that we need to read and write to files in C++.
For the sake of this tutorial, I will start with outputting to files. Before you
can write to a file, you must first OPEN it, like:
file.open("C:\Path\Filename.ext", ios:ut);
Or, if you like, you could do this when you declare the file object, like:
fstream file("C:\Path\Filename.ext", ios:ut);
The ios:ut means that we want to write stuff to the file. You can also use ios::
app to add stuff to the end of the file and thus not erase its contents.
After you open a file, the rest is actually quite simple. You can write to files
in the same way that you write to consoles:
file << "I want to write this to the file!" << endl;
In fact, you can even use the input/output manipulators here, like this:
file << "Azure's Idiotic Autobio" << setfill('.') << setw(20) << "Page 5" << end
l;
Finally, when you are done, you can close the file, like:
file.close();
You could also get stuff from files. The concept is similar to writing stuff, ex
cept the open statement is a bit different:
file.open("C:\Path\Filename.ext", ios::in);
Or, again, you could do this when you declare the file object, like:
fstream file("C:\Path\Filename.ext", ios::in);
Now, just use the variable "file" as if it was "cin":
file >> Variable1 >> Vaiable2 >> Variable3 >> String1;

You can also detect if a file has ended (so you could stop trying to input stuff
) by using the "eof" function:
if(!file.eof()) // File has not ended yet
{
file >> Variable1;
}

Intermediate Stuff: Binary File Input/Output


First of all, what is binary I/O? Well, it's similar to text I/O, but is more fr
equently used for inputting binary data instead of text and numbers.
To perform binary I/O, you must first add an ios::binary to your open statement:
file.open("C:\Path\Filename.ext", ios::in | ios::binary);
Note that the separator is a SINGLE straight line (Binary OR instead of Boolean
OR, if you are curious).
Now, there are two ways to read binary files. One way is character-by-character
using the "get" and "put" statements:
file.get(MyCharacter);
file.put('C');
file.put((char) 210);
The "(char)" operator simply changes the 210 to the ' ' (ASCII #210) character for
compatibility with the "put" statement.
Obviously, reading files character-by-chaacter is quite annoying. In fact, this
was the method that I first used when I made my "Rast Unlocker" utility. Unfortu
nately, the program took hours to read my sample project's .ldb file, which is r
eally only ~100 KB. So...we need a better way to read from these binary files.
Luckily, C++ also offers the "read" and "write" functions, which are used like t
his:
file.read(buffer, size);
file.write(buffer, size);
So...let's assume that you want to stuff four bytes of binary data into a "long
integer" variable. Then, you would use:
long MyLongVariable;
file.read((unsigned char *) &MyLongVariable, sizeof(MyLongVariable));
So...I guess I definitely have to explain that, right? Well, file.read requires
a string buffer (unsigned char *) as its first value. Therefore, we have to pass
the variable by reference so that "read" could actually modify the variable...b
ut the variable is still in long*, so we have to change it to a string buffer fi
rst using (unsigned char *).
The sizeof() statement returns the number of bytes that a variable takes up, whi
ch is required by the read and write functions to ensure that the buffer does no
t overflow.

NOTE: If you did not understand the above explanation, do not worry! Try reading
through my pointer tutorial first, and if you still do not understand this sect
ion, then just pat yourself on the back and remember that this is intermediate s
tuff. You will be able to understand it soon enough. I just inserted it here for
those people who MIGHT understand the technical stuff.
Write is used in the same fashion as read.

Random Access for File I/O


Random Access means that you can access and read from/write to any point of the
file. For example, you could read half of a text file, and then jump to the end.
You could also change certain characters in the middle of the text file, or swa
p random words around. The power is with you .
Random Access works on binary files. If you didn't understand the "read" and "wr
ite" functions earlier, then you will have to use the "get" and "put" functions
to read and write one character at a time.
The most important functions for random access are "seekg" and "seekp", which mo
ves the pointer to a certain place in the file. You use "seekg" to move the get
pointer (Read), and "seekp" to move the put pointer (Write).
The functions share a syntax:
seek?(offset, origin);
Offset is the number of characters that you want to move, and origin can be eith
er "ios::beg", "ios::cur", or "ios::end." What does this mean? Well, origin spec
ifies either "beginning," "current location," or "end." If origin is "beginning,
" then seek? will move the current location pointer to offset characters away fr
om the beginning. Likewise, seek? will move the current location pointer to offs
et characters away from the current location is origin is "ios::cur".
For example, the following will move the current location pointer (get) six char
acters right:
seekg(6, ios::cur);
And this will move the current location pointer (put) at the end of the file:
seekp(0, ios::end);
There are also two functions, "tellg" and "tellp", that will tell you where the
current location pointers are:
cout << "The get pointer is currently at " << file.tellg() << endl;
And that's really all for random access files. I guess I got a little more techn
ical than I needed to, so if you don't understand the last two sections, then do
n't worry. They are more intermediate stuff that most beginners do not need to u
nderstand yet.

Phew! About two and a half hours have passed, and I finally finished another Beg
inners' C++ Tutorial. The next one will cover the basics of classes and OOP...an

d don't worry, I won't put any of the more intermediate stuff on it.
So...until then, so long. And make sure to share any mangos that you stumble upo
n :P.
____

Você também pode gostar