Results 1 to 14 of 14
  1. #1
    SATANICAT's Avatar
    Join Date
    Jun 2006
    Gender
    male
    Location
    In a pineapple under the sea. JAJA.
    Posts
    1,364
    Reputation
    18
    Thanks
    209
    My Mood
    Aggressive

    Learn C++ in as little as one day!

    Thought that the be usefull for some of the C++ kiddys like me :P

    Part One

    Part Two

    Part Three

    Part Four

    Part Five

    [IMG]https://i12.photobucke*****m/albums/a219/cowfurmoo/SATNICAT.jpg[/IMG]
    www.SATANICA*****m
    Can't you tell I made it in paint?
    [IMG]https://i12.photobucke*****m/albums/a219/cowfurmoo/631184778462.png[/IMG]
    ^If you want to join the SATANICAT union add this to your signature. ^


    Take the Magic: The Gathering 'What Color Are You?' Quiz.
    Support me https://www.SATANICA*****m

  2. #2
    EleMentX's Avatar
    Join Date
    Jan 2006
    Location
    de_dust2
    Posts
    3,451
    Reputation
    12
    Thanks
    591
    Nice tut but maybe you should have notepadded them instead of taking us to a different site

    dave might get upset

  3. #3
    SATANICAT's Avatar
    Join Date
    Jun 2006
    Gender
    male
    Location
    In a pineapple under the sea. JAJA.
    Posts
    1,364
    Reputation
    18
    Thanks
    209
    My Mood
    Aggressive
    Comprehensive C++ Tutorial for Beginners - Part 1


    Hi there. If you do not know me (you probably do not), my nickname is AzureFenrir, 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* HELLO 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 parts 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 you 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 yells to DOS, "HEY!!! LOOK AT ME!!! I'M MAIN!!! I'M ALL SPECIAL AND 1337 AND WHATNOT 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 basically group the statements:

    cout << "Hi ATARI!\n";

    and

    return 0;

    together into one block of code. This tells main(), "Oh! Everything inside the braces belongs to me! I'm special and I have all two lines of code!!! Yay!" If you 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...but 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 window." cout << "Hi ATARI\n"; tells DOS to write "Hi ATARI" followed by a LINE FEED (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 you 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 with the semicolon. The semicolon basically tells the compiler that one line of code has ended and another line is about to begin. However, you DO NOT add a semicolon 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 littering 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 ended 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 if it just displayed text continuously...or in computer nerd terms, "All Output and 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 member barges into the room and bombards AzureFenrir with GW Productions? Multi-Purpose Tar and Feathers. Two days and several baths later, a slightly wet AzureFenrir 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 RM2K), 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 contains 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 want the variable to store something else, you can substitute int for something else, 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 with the value zero. If this is omitted, then the variable will start off with a really 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 to build a basic C++ program
    How to write text onto a DOS window
    How to define a variable in C++
    How to 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 operators, 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 conceptual 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 have 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 happen again.

    Anyways, here I am with ANOTHER tutorial on C++. This time, I will continue at where I left off last time and ingrain more and more and MORE AND MORE...(repeated 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 - comments.

    Comments are stuff that has no effect on your program. Basically, it does nothing. 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 program, 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 program does just by glancing at it. However, keep in mind that when you write large programs with extremely lengthy subroutines and coding, comments will seriously help you find the code that you're looking for in an assorted junkyard of stuff.

    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." However, C++ will not be very useful for game programming if the you could only type stuff line-by-line, character-by-character, with no way to manipulate it whatsoever. So, how do we manipulate text?

    Well, before you do any manipulating, you must add another odd # line to your code:

    #include <iomanip.h>

    Yep, another line with that silly #include symbol. Remember from my last tutorial 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 data 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 Dias!\n";

    This yields the result:

    Hello! Bonjour!Buenos Dias!


    Note that the last entry, "Buenos Dias!", is 12 characters long. However, we only 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 setw, flags set with setiosflags will continue to affect the "Stuff" that you write 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 resetiosflags 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 affect all subsequent outputs!


    Displaying Fixed Values Using setprecision

    The C++ setprecision function, when used in conjunction with setiosflags(ios::fixed), can display FIXED NUMBERS, or numbers to a certain decimal point. For example:

    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 with ios::fixed (or ios::scientific). When none of these two flags are set, setprecision specifies the "total number of significant digits in a number." Don't worry about this, as you'll probably never use it anyway.

    setprecision, like setiosflags, will continue to affect every number that you display using cout. To reset the precision, just type setprecision(6), which is usually the C++ default.


    Having fun with setw using setfill

    Whenever you use setw to set I/O width, the unused areas always contain ugly spaces. Well, the good news is...that can be changed by using a function names setfill!

    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 quotes 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 manipulation, 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 elaborate 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 stringname[11]).

    Are you wondering why? Well...I won't tell you why, unless if you share those mangos with me.

    What? I'll be fired if I don't reveal the secret? OK...fine...every C++ string ends 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 stuff 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 NULL character before it intrtudes upon those spaces), it will still print a bunch of strange and unsightly junk after your strings.

    Unfortunately, you cannot set strings by just using something like stringname="xxx". You have to use C++'s string functions, the most commonly used ones being strcpy, strcat, and strlen.

    Before you use these functions, you must add another silly little #include statement:
    #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 contains "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? That 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 quotes (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 characters anyway.

    So...if we use cin.get, what happens if *gasp* the user types more than n characters of stuff?

    Well, C++ will remember the extra stuff and will use it on the next cin statement. Because there is already stuff for it to use, cin will NOT ask the user for information, 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 your 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 empty the C++ storage room. This would force C++ to ask to user for more information, 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 boolean 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 and 1, false and true. 0 means false, and 1 is true. This is very similar to how the 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) otherwise.

    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 value false (0) in temp, because 3 is not larger than five!!! (Well, maybe in other 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 structures, 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 you to run a piece of code if it's conditions are met - that is, if it's inner code 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 statement that it has exclusive control over everything inside the braces! That power-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 large 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 younger than 18!\n";, belonged to the if statement. Since the if statement cannot control the second line, the second message will display, regardless of what you type.

    So...just remember to always include braces, capiche?

    If you've ever used RM2K (or any other scripting/programming language), you should 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 condition in the if statement is NOT met.

    MWAHAHAHAHAHAHA!!! WHEN I PERFECT MY POWERFUL MUTANT ARMY, THE WHOLE WORLD IS MINE!

    That proves that I belong in an asylum...anyway, the else statement MUST immediately follow the end brace } of an if statement. There cannot be ANYTHING (except comments [and some compiler directives]) between the if } and the else statement!!!

    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 younger than 18!\n";
    cout << "ATARI is young!\n";
    } else {
    cout << "ATARI is either older than or exactly 18!\n";
    cout << "ATARI is experienced!\n";
    }
    }

    I don't need to know ATARI's real age, so even if you know it, don't post it, capiche?

    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 combination of two keywords - if and else.)

    Do you understand all this so far? Yes? Good! Now, I'll show you a few new boolean 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 are 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 expressions. For example:

    (2 > 5) && (3 < 4)

    Returns false (0). Although 3 is less than 4, 2 is NOT greater than 5. Because the && 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 tutorial, 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 variable instead of a boolean statement, and has multiple branches depending on what the 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 defaultcode 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 kidnapping 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 may cause the program to display "Hello!" 100 times, or slap someone until they type "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 basically whatever code that you want to repeat. Let's focus our attention on the three parts of the "for" loop, the initialization, condition, and increment statements.

    The initialization statement runs at the very begining of the loop, before any repetition of the blocked code occus. In fact, the code in here will run before the code that you want to repeat is executed ONCE! This code is basically used to initialize a variable (like i) to a number so that it could be used in the rest of the loop.

    The condition statement will end the repetition if it's false. For example, if the condition is, say, i < 11, then whenever i is larger than or equal to 11 (which 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-by-step, using diagrams to show you the actual process of the code. So, for the following 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 being 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 statement 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, we encountered the (}) code, which indicates the end of the for block. Because loops 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 true), 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 run 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 return false. This causes the for loop to skip its code block (and thus not run the 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 loops 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" loops 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 multiple 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 were 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 the 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 program run forever. If you've ever seen windows crash, and nothing seems to be working (not even Ctrl-Alt-Delete) - well, that's probably an infinite loop.

    Finally, you can also have multiple conditions for the conditional statement, but 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++ doesn't care what code you put in the conditional statement, as long as it gets either a true or a false value. If it gets something else (like a dereferenced string), 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 statement returns false. So, if condition is i < 6, then the code repeats until i is NO 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 essentially 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 Key to Continue"). Therefore, this code basically displays "You will press enter or 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 character.

    So...we don't really need to walk through this. The code simply keeps running through the code until it encounters a '\r' character, which indicates that is pressed.

    Oh, and you probably have no idea what '\r' is, and why we are not using the newline '\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'. However, for compatibility purposes, the key will retun BOTH the '\r' and '\n' characters, 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 properly 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 "while" loops, "Do...While" loops check the condition at the very bottom of the code, 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 and set it to 8, but it will not PRINT anything). Why is that? Well, when the system 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 code 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, joyous...ahh...

    *snap*

    Oh wait, where was I? Right. The break statement unconditionally exits out of the 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 the break statement, it will immediately exit the loop, even though the loop is infinite (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 iteration.

    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 the "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 << "The number is " << i << '\n';
    Â Â Â Â if((i % 4) != 0)
    Â Â Â Â {
    Â Â Â Â Â Â Â Â continue;
    Â Â Â Â }
    Â Â Â Â cout << "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 of 4!
    The number is 6
    It is not a multiple of 4!
    The number is 7
    It is not a multiple of 4!
    The number is 8
    The number is 9
    It is not a multiple of 4!
    The number is 10
    It is not a multiple 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 immediately go to the next iteration of the loop, completely ignoring the rest of the code (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 must 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) because of unstability reasons - most programmers believe that jumping around in code 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 assembly.

    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 statements 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 (Introduction to OOP) until the end of this series! This tutorial will simply cover some 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 their 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 ANSI headers), which supports quite a few more modern functions to make your programming 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 functions do not somehow conflict with yours due to an identical name, all ANSI functions and classes are encased in a namespace, which serves to keep them apart from your functions (by keeping them in a different area). The command "using namespace std" simply tells C++ that your program will use the namespace "std" and will not conflict with any of its functions.

    So...what if you do not put this statement on top of your .cpp file? Well, in this case, all of the ANSI classes will still remain in the "std" namespace, and you 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 will 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 the regular ".h" headers. Well, in addition to being the newest C++ trend, the ANSI headers also offer a lot of things that the standard headers doesn't...and all 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 strings 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 annoying. I know I used to HATE the pointer and string errors that came from character manipulation and dynamic string arrays.

    So...what does the ANSI headers offer that will solve this problem? Well, how about 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 the 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 there's room? Why do we need that when we can simply use +=, without needing to check 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, which is quite handy for certain C and older C++ functions (as well as anything that 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 describe 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 right back to old-school structures.

    So what are structs and unions? Well, they are custom data types that you, the user, can create. Both of these data structures can contain multiple submembers of 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 any 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, setting, say, the member2 member of MyNewVariable will do nothing to the member2 member of MyNewVariable2, and vice versa. They are independent variables, and changes 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, which 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 variable'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 portion of the integer member.

    Unions are mostly used for multivariable compatibility in the old C days, but can 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 individual 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++ functions 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 include these parameters:

    return_type function_name(type argument1, type argument2, ...)
    {
    // Code here, Blah Blah
    return return_value;
    }

    There. The arguments are basically custom "variables" that the user can pass to your function to specify something (such as the two numbers that should be added, the interest rate of investment, etc.) With this in mind, let's make the above function more useful by making it 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 assume 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 many lines of code as you want - it doesn't always have to be just one "return" statement.

    Finally, you can make a function return NOTHING (useful for functions that perform 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 function main(). Because they are usually placed under main(), the compiler will compile these functions after compiling main, and you may get an error when the compiler reaches a reference to your function.

    If you didn't understand the above statement, that is OK. Just remember that functions usually go after main, and function prototypes are usually needed for functions 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 must be the exact same as your actual function, except for the fact that it has no coding and is terminated by a semicolon. This prototype will ensure that C++ will know that your function exists, and won't get confusing looking for it and 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 every program, every spreadsheet, every e-mail, every web page, every DrFunk 60-Second Paint Pictureâ„¢, and...well, you get the picture.

    Let's start with the headers. Obviously, file input/output requires its own header, 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 operators 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" << endl;

    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, except 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 frequently 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. Unfortunately, the program took hours to read my sample project's .ldb file, which is really 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 this:

    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...but the variable is still in long*, so we have to change it to a string buffer first using (unsigned char *).

    The sizeof() statement returns the number of bytes that a variable takes up, which is required by the read and write functions to ensure that the buffer does not 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 section, then just pat yourself on the back and remember that this is intermediate stuff. 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 swap random words around. The power is with you .

    Random Access works on binary files. If you didn't understand the "read" and "write" 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 moves 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 either "ios::beg", "ios::cur", or "ios::end." What does this mean? Well, origin specifies either "beginning," "current location," or "end." If origin is "beginning," then seek? will move the current location pointer to offset characters away from the beginning. Likewise, seek? will move the current location pointer to offset characters away from the current location is origin is "ios::cur".

    For example, the following will move the current location pointer (get) six characters 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 technical than I needed to, so if you don't understand the last two sections, then don't worry. They are more intermediate stuff that most beginners do not need to understand yet.




    Phew! About two and a half hours have passed, and I finally finished another Beginners' C++ Tutorial. The next one will cover the basics of classes and OOP...and 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 upon :P.
    ____

    [IMG]https://i12.photobucke*****m/albums/a219/cowfurmoo/SATNICAT.jpg[/IMG]
    www.SATANICA*****m
    Can't you tell I made it in paint?
    [IMG]https://i12.photobucke*****m/albums/a219/cowfurmoo/631184778462.png[/IMG]
    ^If you want to join the SATANICAT union add this to your signature. ^


    Take the Magic: The Gathering 'What Color Are You?' Quiz.
    Support me https://www.SATANICA*****m

  4. #4
    poulet28's Avatar
    Join Date
    Jul 2006
    Gender
    male
    Location
    ...a Far Away Land...
    Posts
    418
    Reputation
    10
    Thanks
    12
    I think clark that you should learn what is NOTEPAD.
    NOW.

  5. #5
    SATANICAT's Avatar
    Join Date
    Jun 2006
    Gender
    male
    Location
    In a pineapple under the sea. JAJA.
    Posts
    1,364
    Reputation
    18
    Thanks
    209
    My Mood
    Aggressive
    kk here then

    [IMG]https://i12.photobucke*****m/albums/a219/cowfurmoo/SATNICAT.jpg[/IMG]
    www.SATANICA*****m
    Can't you tell I made it in paint?
    [IMG]https://i12.photobucke*****m/albums/a219/cowfurmoo/631184778462.png[/IMG]
    ^If you want to join the SATANICAT union add this to your signature. ^


    Take the Magic: The Gathering 'What Color Are You?' Quiz.
    Support me https://www.SATANICA*****m

  6. The Following User Says Thank You to SATANICAT For This Useful Post:

    legacyofanoob (11-20-2013)

  7. #6
    poulet28's Avatar
    Join Date
    Jul 2006
    Gender
    male
    Location
    ...a Far Away Land...
    Posts
    418
    Reputation
    10
    Thanks
    12
    Quote Originally Posted by CLarK
    kk here then
    Thank you man.

  8. #7
    Darky's Avatar
    Join Date
    Mar 2007
    Location
    In my house!
    Posts
    583
    Reputation
    12
    Thanks
    4
    thx for tutorial it realy helped me !

  9. #8
    dragoonleader69's Avatar
    Join Date
    Jul 2007
    Gender
    male
    Location
    Behind you.........
    Posts
    118
    Reputation
    10
    Thanks
    0

    Insert title here >______<

    Good work got through 1 paragraph and was lost lol. oh well i will learn
    +rep

  10. #9
    jayhosting's Avatar
    Join Date
    Sep 2007
    Gender
    male
    Posts
    3
    Reputation
    10
    Thanks
    0
    nice tut

  11. #10
    federosh's Avatar
    Join Date
    Aug 2007
    Posts
    5
    Reputation
    10
    Thanks
    0

    help

    hi i need help

  12. #11
    Lovepreet's Avatar
    Join Date
    Sep 2007
    Location
    www.mpgh.net
    Posts
    311
    Reputation
    89
    Thanks
    13
    Awsome... It Look's Great... But Is Vb C++ 08 The Right One To Use ?

  13. #12
    radnomguywfq3's Avatar
    Join Date
    Jan 2007
    Gender
    male
    Location
    J:\E\T\A\M\A\Y.exe
    Posts
    8,858
    Reputation
    381
    Thanks
    1,823
    My Mood
    Sad
    Your asking if "Visual Basics C++" is the right one to use? Uhm its called VC++. Download the updated one download VC++9.0 Thats the right one to use, thats the one i'm using anyways.

  14. #13
    sukh13's Avatar
    Join Date
    Aug 2007
    Gender
    male
    Posts
    64
    Reputation
    10
    Thanks
    7
    hay lovepreet ru indian? but iam soo if u wenna lern how to make hack download vb6 thats the 1 easy to use orr u already knw then my bad

  15. #14
    beatzwithin's Avatar
    Join Date
    Sep 2007
    Posts
    17
    Reputation
    10
    Thanks
    0
    thx alot for this guy...i dont know how u guys find the time to write these tuts...big uppz tho...as u can see by mt post im new but u will b seein more and more of me in time l8rz

Similar Threads

  1. WoT PZ tank + one day of premium + 300 gold
    By Detroilen in forum World of Tanks Hacks & Cheats
    Replies: 10
    Last Post: 12-03-2011, 05:13 AM
  2. one day....
    By Gourav2122 in forum General
    Replies: 28
    Last Post: 09-14-2007, 04:12 AM
  3. One of those days.
    By wr194t in forum General
    Replies: 10
    Last Post: 09-08-2007, 08:31 PM
  4. [a little off topic] sellin 7 day ak47 code for warrock
    By m164life in forum WarRock - International Hacks
    Replies: 8
    Last Post: 03-07-2007, 08:33 PM
  5. Replies: 1
    Last Post: 05-20-2006, 06:17 PM