# C++: The Basics

## Recommended Posts

mxma1    140
I spent two hours writing this on the gd.blacksummit.co.uk forums but I figure it might do good here too so here it is. For those of you who have little or no experience with C++, I'll teach you enough to learn to write a simple text-based RPG. This is written to work in Visual C++ 6. It will run a little bit differently in Dev-C++ so I will cover the differences in later posts. Let's start off with a simple program that displays "Hello World!" to the users. This is the most common first program a programmer learns.
// Hello World! Program
#include <iostream.h>

int main()
{
cout <<"Hello World!"<<endl;
return 0;
}


Let's break down this code to further understand what is going on.
// Hello World! Program


This line of code does absolutley nothing. This is called a comment. It is used to help a programmer understand what the lines of code mean or do when he/she looks back. A comment is declared with two forward slashes. You can comment anywhere including at the end of a line of code. It is smart to comment your code when you are showing your code to other people.
#include <iostream.h>


This line of code tells the compiler to include a file called "iostream.h". These files are called header files and have prewritten functions for a programmer to use. This particular header is an Input/Output Stream header that handles all the input and output of the program. There are many headers such as headers that deal with graphics or networking. The inclusion of headers will almost always be the first lines of code in your program.
int main()
{


This line of code tells the compiler that the function main has started (the start of a function or a scope is declared with { and the end with }). Main is where your program always starts. From here you do the main coding. This would be like the front door to your house, from it you can acess all parts of your program. the "int" means to declare your main as a return type of integer. This is not really important right now but you'll learn more about return types when we go over functions.
    cout <<"Hello World!"<<endl;


This line of code is the line that tells your program to print "Hello World!" onto the screen. Output lines can almost be related to old trains. You have your different carts and the connectors. "cout" would be the front cart, it tells the compiler to print the next cart ("cout" is included in iostream.h, as well as "endl"). The "<<" is like the connector of t he carts. "Hello World!" is the cart that "cout" prints out. You can print almost anything using this line of code; "game over", "level 4", "restore2" etc. When printing out a string such as "Hello World!", the string has to be in quotation marks ("") in order for the line of code to work correctly. After that we have another connector then "endl;". "endl" tells the compiler to endline, or start a new line. This means that the next thing printed will be on a new line. The semicolon (;) is like the tailpeice to the train, you need it for most commands in C++. You need this semicolon to tell the compiler that it is the end of the train and you can start a new command on the next line.
    return 0;


This command tells the program that int main() is done. This is called the return. Because the int main() function is not called by anything, it can't return anything. I know this doesn't make much sense but I'll explain functions in a little bit. This generally tells the program to end because there is nothing else the program needs to do. (NOTE: if your programs just pops up and closes immediatley, you need to do one of two things, either click compile and run seperatley, instead of ctrl+f5, or add #include <windows.h> and system("pause"); to every program so that the Hello World! program would look like this:)
// Hello World! Program
#include <iostream.h>
#include <windows.h>

int main()
{
cout <<"Hello World!"<<endl;
system("pause");
return 0;
}


That's it! You just wrote your first program using C++! You are well on your way to making a Text-RPG! (Try Me!: Using what you have learned, write a program similar to the Hello World! program, but instead make it display your name and your favorite color. You can do multiple lines of output just by making another line of cout <<""<<endl;. Good luck!). Figure out the Try Me? If not then here would be how to do it, using my favorite color and my name:
#include <iostream.h>

int main()
{
cout <<"Andrew Flores"<<endl;
cout <<"Grey"<<endl;
return 0;
}


OK, now that you understand the basics of Output to the screen, lets move on the variables. Variables are like empty boxes that can contain information. Lets say I have a box called myFavoriteNumber. This box can contain any number but since my favorite number is 1337, myFavoriteNumber is equal to 1337. So let's write a program that displays my favorite number.
#include <iostream.h>

int main()
{
int myFavoriteNumber = 1337;
cout <<myFavoriteNumber<<endl;
return 0;
}


This looks very similar to the Hello World! program as you can see but with some slight changes.
    int myFavoriteNumber = 1337


The first word in the line of code is "int". This declares that our new variable will be an integer. This means that my variable will be a whole number that is not negative. (1, 3, 453, 3453 are all examples of integers; .234, -123, -.9 are all examples of non-integers). The next part of the code is "myFavoriteNumber". This tells our compiler that our new integer will be called myFavoriteNumber. You can name your variable anything you want but the first letter has to be lower case and it can only contain letters and underscores (playerHP, player_HP, and _playerHP are all valid variable names while PlayerHP, player1_HP and 2playerGame are not). The next part is "=". This is pretty straightforward. It means that our new integer called "myFavoriteNumber" is equal to. "1337", this makes our new integer called "myFavoriteNumber" equal to 1337. So now I have created my variable, or box that is an integer, and it contains the number 1337.
cout <<myFavoriteNumber<<endl;


This is just like how we displayed "Hello World!" but there is a small difference. Since myFavoriteNumber is a predefined variable, we do not put quotations around it. If we did, the output would be "myFavoriteNumber", not "1337". All outputted variable will not have quotation marks around them, this displays their value instead of their name. The other parts of the code are just like our Hello World! program. There are a few types of variables. here is a simple chart to show you the different types: int - Integer; can hold a positive whole number up to a couple hundred thousand char - Character; can hold a single letter bool - Boolean; can hold true or false (not in quotation marks) float - Float; can hold decimal values like .34 or 13.37 double - Double; this is exactly the same but it can hold up to twice the max of an integer (like if the integer's max is 200,000, then double can hold a number up to 400,000) I'm sure you were wondering how to create a variable that holds a player's name. There is a way to do this but I'll cover that in next. As you can see, variables are well...sexy. They can be used for so much. We can do a lot with them!:
bool playerIsDead = false;
int pistolBullets = 4;
int playerHP = 50;
float temperature = 94.3;


(Try Me!: Using what you have learned, write a program that displays this:
My Weight:
143


Using the variable
int weight


Good luck!). Figure out the Try Me? Here's how to do it:
#include <iostream.h>

int main()
{
int weight = 143;
cout <<"My Weight:"<<endl;
cout <<weight;
return 0;
}


Good job you did it! Now let's cover input and arrays. So lets says we wanna make a program like the My Weight program but instead, it takes a user's input and displays their weight. This is how to do it:
#include <iostream.h>

int main()
{
int weight;
cin >>weight;
cout <<weight<<endl;
return 0;
}


Ok, new things that you probrably noticed are that I declared the integer weight without setting it equal to anything, there is no endl after "Enter Your Weight", and there is a new command "cin".
    int weight;


Although you've seen this command before, it's different; it's not set equal to anything. This is how it works. We created a box that contains nothing called weight. We do this so that when the users types his/her weight, the box is ready to take in the number. You do not have to set a variable equal to anything when you declare it.
    cout <<"Enter Your Weight: ";


You've only seen this code before with the attached "<<endl" but this time we do not require a new line of code. This is because the user can type his/her number right after "Enter Your Weight". We can also use this for things like:
    cout <<"Your Weight: "<<weight<<endl;


After, the user has typed his/her weight, the screen will look like this:
Enter Your Weight: 143


Do you see how there is no new line in between "Enter Your Weight: " and the number? Ok, so we have our prompt asking for the weight so now lets allow our user to type in his/her weight.
    cin >>weight;


This a new command. It's similar to cout and also comes from iostream.h. It works like this. "cin" means instead of outputting the next line, it takes input from the user and sets the next cart (in this case, the integer weight) equal to the user's input. So now, instead of having our empty box called weight, it's now full with the number that our user has typed. The next 3 lines you should understand. So now you know how to take input from the user. (Try Me!: Write a program that ask's the user for his age, weight, and favorite number and display them all. Use the variables:
int age;
int weight;
int favorite;


Good Luck!). Here's the answer to the Try Me!:
#include <iostream.h>

int main()
{
int age;
int weight;
int favorite;

cout <<"What is your Age?: ";
cin >>age;
cout <<"What is your Weight?: ";
cin >>weight;
cout <<"What is you Favorite Number? :";
cin >>favorite;

cout  <<"Your Favorite Number Is: "<<favorite<<endl;

return 0;
}


I used a blank line to seperate the different parts of my program. You can do this too to make your code more organized. Are you ready for arrays? Here they come! (I had to have at least ONE cheesy little line that you'd read in a book). Checkpoint One: Arrays: Arrays work like this. It creates a variable but makes different sections of it. It'd be like if you have a box, but inside it has several different boxes. Let's make a character array for a player's name:
#include <iostream.h>

int main()
{
char name[10];
cout <<"What is your name?: ";
cin >>name;
cout <<"Hello "<<name<<"!"<<endl;
return 0;
}


As you can see, declaring arrays is similar to declaring variables but it has an attached number.
    char name[10];


This line creates an empty character variable called "name" with 10 empty slots. One important thing to know is that the array has 10 slots but it does not go from 1-10, it goes from 0-9. This line means our player's max length for his/her name is 10 letters. If we made a pre-defined character array for say a monster's name, we would have to give it enough slots to accomodate the name:
    char enemy[20] = 'TehHolyFlyingMonkey';


As you can see, we cannot have spaces in the character array. So how would this work? You can use the array to display, say only the first half of the name. Because our character array enemy is equal to "TehHolyFlyingMonkey", that means that (remember that 0 is the first character 19 is the last):
enemy[0] = "T";
enemy[1] = "e";
enemy[2] = "h";
// So on and so forth


As you can see, we can now utilize each letter of the word seperatley. (Try Me!: This one is tough so be prepared! (Ok, change the cheesy line counter to 2). Write a program that asks the user for a 5 letter word and displays that word backwards using an array called "word[5]". Good luck!). Was the Try Me! too difficult? (I know that I didn't explain arrays all that well but it's 4:00AM in the morning here in Japan and I've been up all night writing this so I'm tired). Here's the code:
#include <iostream.h>

int main()
{
char word[5];
cout <<"Type a 5-letter Word: ";
cin >>word;
cout <<word[4];
cout <<word[3];
cout <<word[2];
cout <<word[1];
cout <<word[0];
return 0;
}


You did it! You made it to the first checkpoint in the C++ Basics. The next post that I write (hopefully tomorrow) will cover Functions, If commands and Loops. Happy coding and always feel free to write me an email or IM me on AIM asking me any questions you need help with. AIM: AzNeLm0 Email: mxma1@yahoo.com [Edited by - mxma1 on August 6, 2004 2:49:35 AM]

##### Share on other sites
snk_kid    1312
I don't mean to be rude/anal but your code has errors, usage of deprecated header files is a no no, and using non-standard library headers for someone completely new i think is not a great idea. I didn't actually read any of it but glanced at the code.

##### Share on other sites
red_sodium    216
As viewed from a C++ intermediate/advanced programmer, nice tut, i just skimmed over it but it looks good enough for the very basics (first tutorial). Just two things:

Quote:
 This line means our player's max length for his/her name is 10 letters.

Actually, it's only 9 letters, due to the NULL terminating '\0' character at the end of a char array (when used as a string).

Also, your code sections do not work, i think you have to make [CODE] and [/CODE] into [ code ] and [ /code ] (without the spaces).

Good luck writing the rest!!!

##### Share on other sites
stormrunner    720
indeed. not to be rude as well, but as a point of reference, mxma1, always copy & paste from a program that works. i.e., having examples is great, but its clear that you haven't checked them against the shrewdest critic of them all - the compiler, which would scream at half of these. you're missing >> after a cin, and to initialize an array of characters singly, use the ' ', not " ". and #include was spelled wrong somewhere. just fyi - otherwise its a good start.

##### Share on other sites
mxma1    140
Thanks for letting me know of the errors. Hmm this is the way I was taught from 3 different books and a C++ beginner's class. I must've been screwed over 4 times if this is not the correct way to do it D:. I'm real sorry about the laziness. It's 4 in the morning here in Japan and the motivation to actually check everything and go over all of everything is just REALLY low.

##### Share on other sites
Eriond    187
The thing that is most irritating for a beginner is code that won't compile, atleast that's what I think. Your code won't compile on msvc 7.1 or gcc/mingw (which dev-c++ uses). Not to sound rude, but if you can't write code that will compile on standards compliant (sp?) compilers I don't think you should write a tutorial imho.

##### Share on other sites
mxma1    140
Ok I fixed some more errors. By the way, 10% of that code is not code, you have to read the tutorial. Like the initialization of each part of the array, that's not supposed to be compiled code, it's a like figure to show how things work. Also, what part doesn't compile? Or all of it? because I just tested it and it works (except, since I'm using dev-c++ i had to change iostream.h to iostream).

##### Share on other sites
snk_kid    1312
I have a couple of suggestions if your really going to do this, talk about namespaces first, prefer using C++ string type over C-style strings when teaching before the other way round it will be less painful. Maybe talk about stringstream types so people know how to convert a string to other types & the other way round this would be very useful i think. Try to use as much of the standard library than non-standard or low-level features of the language.

##### Share on other sites
mxma1    140
I understand where you're coming from but this was not intended to be some full blown book or something like that. I wrote this simply because someone on gd.blacksummit.co.uk said that maybe there should be something for the beginngers to start out on and we (on that forum) are talking SIMPLE text-based RPGs and this imho is the easiest user i/o there is. And I always learned this stuff on VC++ 6 where you didn't generally need namspaces for simple stuff like this but obviously that's not the standard so I need to get in the habit of using namespaces. My bad on that part. Gah can't find the mispelt #include. Or maybe it's just 5am and I've been up all night and my mind is starting to shut down.

##### Share on other sites
snk_kid    1312
Quote:
 Original post by mxma1I understand where you're coming from but this was not intended to be some full blown book or something like that. I wrote this simply because someone on gd.blacksummit.co.uk said that maybe there should be something for the beginngers to start out on and we (on that forum) are talking SIMPLE text-based RPGs and this imho is the easiest user i/o there is. And I always learned this stuff on VC++ 6 where you didn't generally need namspaces for simple stuff like this but obviously that's not the standard so I need to get in the habit of using namespaces. My bad on that part. Gah can't find the mispelt #include. Or maybe it's just 5am and I've been up all night and my mind is starting to shut down.

VC++ 6 was made while C++ was being standardized so there are problems with it, you can download service packs to sort out alot of issues but you might be better off downloading the free version of VC++ 7.1 compiler (no IDE thou).

##### Share on other sites
stormrunner    720
you misspelt #include on one of the "Hello World" programs - #inlude <windows.h>.
Quote:
 As you can see, we can now utilize each letter of the word seperatley

the section above that should use ' ' instead of " ". i know you're explaining it, but again, if one of the people reading that was to try it, it wouldn't compile, and the errors resulting from that would not be inteligible to a noob. using that with dev yielded
char hex[3];hex[1] = "H"; // which should be hex[1] = 'H';/* the compiler wrote ::    invalid conversion from 'const char*' to 'char*'*/

a noob won't know what the hell that means, or how to fix it.
which is probably why starting with std::string makes that easier.

##### Share on other sites
mxma1    140
Actually, like I said, I'm in Japan so I'm stuck with Dev-C++ and I honestly can't stand it. Not because I don't know how to use it or what not, I just prefer VC++ 6 over it anyday. Anyways, so I couldn't test my code completley because I don't have VC++ 6 right now. But I don't think I'll be writing anymore tutorials because I don't think people think they are any good so there's no point.

##### Share on other sites
noVum    170
Ooooh, come one, don't use headers that were NEVER in any standard (despite that standard is 7 YEARS old) in a tutorial.
Visual C++ .NET 2003 won't even compile code with them anymore

##### Share on other sites
mxma1    140
I don't know if you guys read but there is a thing in the VERY beginning that says "made to work with VC++ 6". I know for a fact that code works with VC+ 6.@@

EDIT: And WTF..i payed like 300+ for a week class at UC Berkley and another at UC San Diego and they teaching the wrong stuff...those bastards.

##### Share on other sites
KingRage    100
Thanks for the tutorial I read it over and it was a good review of what I'd been learning in the last week. I'm excited to read your next one on functions :) Also a suggestion if you could sort of put how it would be used in a text-rpg that would be nice :D

##### Share on other sites
mxma1    140
Wow that kinda sux because I'm not really going to be writing anymore tutorials becuase they suck.

##### Share on other sites
merlin9x9    174
Good, because the world is already full of tutorials and books written by people who don't know what they're doing, and that perpetuates the system.

##### Share on other sites
stormrunner    720
Quote:
 Good, because the world is already full of tutorials and books written by people who don't know what they're doing, and that perpetuates the system.

i'd ammend that sentence to "because the world is already full of tutorials and books written by people who don't have a point and who don't know what they're doing". those annoy me, the ones that act like they're a c++ bible or something, and simply dish out enormous amounts of random information for no apparent reason other than to prove they can. i see nothing wrong with mxma1 writing tutorials on creating a text-based rpg, as long as he sticks with it, and uses a compiler to check his code.
Quote:
 Wow that kinda sux because I'm not really going to be writing anymore tutorials becuase they suck

so you made some mistakes - welcome to the real world.
lets straighten out a few points.
first, "because they suck" is a poor excuse for giving up. what is this based on ?
second, you shouldn't care what those of us who criticised your tutorial think. the post by KingRage says it all; it was an decent tutorial for noobish programmers. those comments are the ones that you should care about - the comments from the intended audience of beginning programmers. in case you didn't notice, no one but KingRage actually fits that description. so perhaps you should reconsider.
fyi - anything in VC can be made to run in dev, especially these simplistic programs.

##### Share on other sites
DaemonMagus    122
I'm new to C++ and I'm using the Sams Teach Yourself C++ in 21 days book. I read through everything and noticed some errors, but if you keep working on it, it could become valuable for someone. Another thing is by working on this, you'll be able to learn stuff yourself, and allow your code to work with the standard.

##### Share on other sites
Q-Parser    168
The one who didn't make any mistake in his/her first program, be doomed! I always forgot the semicolons at the end of line.

##### Share on other sites
mxma1    140
Ok, this is to all you people who don't know how to read

"THIS IS WRITTEN TO WORK WITH VC++ 6, IT WILL RUN DIFFERENTLY IN DEV-C++".

Second, I thought this would help, not start a flame, I don't mind comments from people saying error this you made a syntax error there but "you're stupid teaching non-standard things to beginners"; ok, if you want to spend 2 hours writing a tutorial the right way, I'm down for supporting you but critizing how I do C++ and the way I learned from various resources and several classes does not help anybody in anyway. Third, stop telling me to make it work in other compilers because this is how I do it and I thought that the majority of people use VC++ 6 and I do not have to make it work in other compilers if I don't want to, if you'd like to redo all my code and make it work in Dev, go for it. Fourth, this is another one for you non-readers :D, SOME OF THAT CODE ISN'T MADE TO COMPILE, IT'S EXAMPLES OF OUTPUT, AND FIGURES TO HELP FURTHER UNDERSTAND WHAT I'M TRYING TO EXPLAIN. Kthx.

##### Share on other sites
snk_kid    1312
Quote:
 Original post by mxma1Ok, this is to all you people who don't know how to read"THIS IS WRITTEN TO WORK WITH VC++ 6, IT WILL RUN DIFFERENTLY IN DEV-C++".

Don't take this offensively in anyway i'm only trying to suggest what would be best. If your going to write tutorials on C++, then write C++ code acccording to the standard and not works with VC++ 6, you'll only end up having your hand bitten to thous you've fed later on.

##### Share on other sites
Guest Anonymous Poster
int declares a variable that can hold a value between -2,147,483,648 and 2,147,483,647.

Be sure to correct if wrong, I only glanced at it all.

##### Share on other sites
petewood    819
Quote:
 Original post by mxma1Ok, this is to all you people who don't know how to read"THIS IS WRITTEN TO WORK WITH VC++ 6, IT WILL RUN DIFFERENTLY IN DEV-C++".

You could write it correctly in VC++ 6 and it will work in dev-c++ as well.

It's probably best to change it to be correct rather than fight over it. I can't see the discussion getting any better if you don't.

##### Share on other sites
merlin9x9    174
Quote:
 i see nothing wrong with mxma1 writing tutorials on creating a text-based rpg, as long as he sticks with it, and uses a compiler to check his code.

Oh, well, if it's okay with you, then that's good enough for me.