C++: The Basics

Started by
27 comments, last by Tiffany_Smith 19 years, 8 months ago
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;
    cout <<"Enter Your Weight: ";
    cin >>weight;
    cout <<"Your Weight: "<<endl;
    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 Age Is: "<<age<<endl;
    cout  <<"Your Weight Is: "<<weight<<endl;
    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]
Advertisement
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.
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 and into and (without the spaces).

Good luck writing the rest!!!
"Learn as though you would never be able to master it,
hold it as though you would be in fear of losing it" - Confucius
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.
- stormrunner
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.
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.
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).
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.
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.
Quote:Original post by mxma1
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.


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).

This topic is closed to new replies.

Advertisement