Accessing multiple variables using another variable

I'm actually not even sure what it's truly called, but I know that you can access multiple variables with numbers using []

Ex.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
include <iostream>

using namespace std;

int main()
{
int x = 1;
char line1[]="Line #1";
char line2[]="Line #2";
char line3[]="Line #3";
char line4[]="Line #4";

while (x < 5)
{
cout << line[x][] << endl;
}

/*

Output should be:

Line #1
Line #2
Line #3
Line #4

*/
}


I'm getting a lot of errors, but I do know that it's something similar to that
DavidScript wrote:
I'm actually not even sure what it's truly called, but I know that you can access multiple variables with numbers using []
I think what you're after is something called an Array.

See the following link for a tutorial: http://www.cplusplus.com/doc/tutorial/arrays/

I think you want an implementation something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
    string line[4];

    line[0] = "Line #1";
    line[1] = "Line #2";
    line[2] = "Line #3";
    line[3] = "Line #4";

    for(int i = 0; i < 4; i++)
    {
        cout<<line[i] <<endl;
    }

Also:

Notice that I used a for loop to iterate through the array, this is because the size of an array is ALWAYS fixed, so if you know the number of iterations then it is better to use a for loop.

If you are not familiar with the string class see here: http://www.cplusplus.com/reference/string/string/

I hope this helps!

EDIT: Added some extra information about the string class and using for loops with arrays.
Last edited on
You have NO idea how stupid I feel


Thanks anyways
Topic archived. No new replies allowed.