Permalink
So, you’ve got a fancy compiler up and running. Get yourself a .cpp file up and running. I’ll be using XCode, so it’s already done for me. If it isn’t done for you, then just do the standard File->New and then name it something along the line of main.cpp.
This is what main.cpp as created by XCode will look like (although yours will probably have different colors.)
What is all of this?
Well, let’s take it line by line.
#include <iostream> is, believe it or not, an include statement. This simply tells the compiler, “Hey bro, make sure you remember to use all of this stuff. The thing within the < > is a file or library. Don’t worry about this too much. For now, I’ll tell you what to include.
After that is “int main (int argc, char * const argv[]).” This line can be a bit intimidating. WTF does all that mean? Well, the stuff inside the parentheses are command line arguments. For now, just delete everything so that it reads “int main()”. What does that mean though? Well, it’s the main function. It’s just the thing that holds all the stuff you want to do.
What about that crap inside of it?
Well, the two backslashes denote a comment. So, anything behind // isn’t compiled. The “std::cout « “Hello, World!\n”;” portion is just printing it to the screen. You can think of “cout” as the print function. The “std::” portion is just telling the compiler where to look. I personally think that’s an ugly way of doing it, so I’ll tell you how to fix it. Promise.
So, you know how to get the file running and you sort of understand what the photo above is. Now what? Let’s make a program to get your name and tell you hello.
We’ll need to start with somehow telling the user that the program needs to know the user’s name. We can do this with the “cin” command. It’s pronounced see-in. This is pretty much the opposite of “cout.” But wait, remember how we had to put “std::cout” back up there? Yeah, I don’t like that. I prefer to put a simple little line in that fixes that. Right under your include statement, put “using namespace std;”. This simply lets the program know that it can throw “std::” in front of whatever needs it. Thank me later.
So, real programming talk. Here’s what needs to happen. We can use the “cin” command to store input to a variable. The command would look like this: “cin » name;” You’ll notice that the « is now ». That’s just saying that we want to input the information instead of output it.
So, we now have stored the data into a variable named “name,” which you need to have declared beforehand.
Now we want to output this. We also want to include a message…hmm….how about, “Hey there [name]”. How would we do that? Well, it’s simple. Just remember how we did “cout” earlier. Here’s how the command would actually work out: “cout « “Hello ” « name;”
Bam. Now, as I’m sure you’ve figured out if you tried to run that, there are a few things not included. But you should understand it! Here’s the actual code that should run.
