DarK_DemoN Member
Points : 6144 Posts : 381 Reputation : 25 Join date : 2011-01-25 Location : Hacking Kingdom
| Subject: Lesson 9 - Strings and Arrays Tue Jan 25, 2011 1:08 pm | |
| Lesson 9: Strings and Arrays in C++As of now, you’ve only used numbers and characters. Now you can finally use strings. I’m going to make this short and sweet, but it can be complicated. First, initializing. You have to include a new header file: - Code:
-
#include <string> Then you type: - Code:
-
string varName; And that’s it. To get strings as input, you type: - Code:
-
cin >> varName; NOTE :: THIS ONLY TAKES INPUT UP UNTIL YOU HIT THE FIRST SPACETo get a whole line of text is more complicated. You can use a c style string. - Code:
-
string mystr; cout << “Enter a your first and last name: “ << endl; getline(cin,mystr); cout << “Hello, “ << mystr.c_str() << endl; And that’s pretty much it for now. Strings have awesome member functions that can tell you their size and all that. But I’ll save that for another lesson. For now, just read the next section. So far you’ve worked with single variables. These can be useful for say, storing a name. But what if you want to store someone’s name, address, phone number, likes, dislikes, family, friends, and who knows what else? Then its time to use an array. An array is basically a collection of variables that all belong to the same “parent”. An array can have two elements or it can have 5,000. Here is a simple array with two elements: - Code:
-
int array[2]; This array holds two elements. I can access these elements using indexing: int array[2]; array[0] = 200; cout << “array[0]” << endl; This would print the number 200. To make arrays easier to understand, you can use integer variables to remember where things are stored. For example: Suppose you want to store someone’s name, last name, and pets name. You could store these in an array like so: array[2]. Say array[0] = name, array[1] = last name, and array[2] = pets name. This is a great way to use arrays, but it can get confusing. How do you remember where certain things are stored? You don’t want to get someone’s name and their pet’s name mixed up. What you can do is this: - Code:
-
int NAME = 0; int LAST_NAME = 1; int PET_NAME = 2; array[2];
// Now, later in the program you are thinking, “Now which number was the Last Name stored at?”. // You don’t have to remember, just type the following:
cout << “Last name: “ << array[LAST_NAME] << endl; This prints the element of thet array at the specified position: LAST_NAME which equals 1 which is where all the last names are stored. |
|