C++ Tutorial Part 2

CMPC :: Computing :: Programming :: C++

Go down

C++ Tutorial Part 2

Post by Unchained on Thu Jan 28, 2010 8:29 am

C++ tutorial PART 2!

Today I'm going to introduce the concept of variables. Pretty much a variable is a container that can only hold a certain type of thing.

Now the 2 types of variables that I would assume are used most are "int" and "string". An int is a container for an integer (number) and a string is a container that holds a string of characters. (a sentence?) You may have noticed that I said those two are the most used, not the only ones, there are several others such as "char" which holds a single character.

How we create a variable is this:

Code:
int NAME;

You say the type, then you give it a name, usually describing what it can be used for. Pretty simple right? You can even give it a value if you want.

Code:
int NAME = 1;

As a note, in order to use string, you need to add the following line to the beginning of your program.

Code:
#include <string>

Now in the last tutorial you may have noticed that I used cout to output text (c-OUT wink wink) and you would be right if you guessed that there is a cin, it gets user input from the keyboard and stores it in a variable.

For many cases you will be using the following code:

Code:
cin >> VARNAME;

Its pretty basic code and is often used, but the problem with it is that cin doesnt like spaces, so in code where spaces are required the following is better.

Code:
getline(cin, VARNAME);


Now lets see how this all fits together ok?

Code:

#include <iostream>
#include <string>

int main()
{
int num1;
int num2 = 2;
string STR1;
string STR2;

cout << "Input a number.\n\n";
cin >> num1;
cout << "Input a word.\n\n";
cin >> STR1;
cout << "Input a sentence.\n\n";
getline(cin, STR2);

num1 = num1 + num2;
cout << num1;
cout << STR1;
cout << STR2;
cin.get();

return 0;
}


I did come pretty confusing things there I'm afraid, I added the two variables and stored the result in num1. Can you find where I did that? Yes you can add them, in fact, for your homework I'd like you to play around with +, -, *, /, and %.(the last is remainder)
avatar
Unchained
Mod

Posts : 448

Back to top Go down

Back to top

- Similar topics

CMPC :: Computing :: Programming :: C++

 
Permissions in this forum:
You cannot reply to topics in this forum