Escolar Documentos
Profissional Documentos
Cultura Documentos
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
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.
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
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
}
}
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";
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 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:
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
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.
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).
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).
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.
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.
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
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;
}
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.
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.
____