Gw Temp

Menu

Tutorial - 'Comprehensive C++ Tutorial for Beginners - Part 2' by AzureFenrir

An item about Programming Languages posted on

Blurb

AzureFenrir's long and descriptive tutorial about C++ continues. Any beginner out there wishing to learn C++, check this out, and the first part if not already.

Body

Comprehensive C++ Tutorial for Beginners - Part 2


CORRECTION FROM LAST TUTORIAL:

There is no single in C++. The correct type should be float.



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::oct
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!

[AzureFenrir disappears into thin air.]