Possible to use varibles contents in code?

Hey guys, I am wondering if there is a way to use the value/contents of a variable in code as a function call or something similar. Essentially using a variable as another variable. For example lets say I had the following code (using standard name space):

1
2
3
4
  int iLength;
  int iSelect = 1;
  string sString1 = "hello";
  string sString2 = "hi";

and I wanted to find out the length of string 1. Traditionally I would just do:
 
  iLength = sString1.length()

and get 5. However, is there a way I could use the value of the "iSelect" variable in my code to do the same thing? Something like:

 
  iLength = sString(iSelect).length();


I just used parenthesis as an example (im not sure what the syntax would be) but the point is that the program would read that line as "iLength = sString1.length();" getting the "1" from iSelect.


I need to be able to do this because I am making a game in which there is a lot of logic that changes based on the room you are in, and this would really help clean up my code because the only way I know how to do it now is have an if statement for every possible room and then the code copy and pasted for each statement. I have about 40 rooms so as you can imagine if I want something to happen in a room that takes 10 lines of code that would be 400 lines instead of 10 just because I need to copy the code and use an if statement for each room.

I will explain a bit more if it helps get the point across, but if you understand already just skip this. Each room has a string associated with it that holds the items in the room. For example I have a room called "10" (so if your in room 10 the iLocation variable equals 10) and then a string called s10, and s10 = "ball bat glove bar". So if I wanted to do any manipulation of the items in that room ( or any room) I'd have to do something like s10.append or s10.erase and then have that same code 40 times (i.e. s11.append , s12.append) for each room under an if statement (i.e. if (iLocation == 10) ...) so that the program manipulates the correct string. It would be MUCH easier if I just had one iteration of my code that could be something like s(iLocation).append so that it would work for EVERY room because it would perform the action on the room items string based on what room you are in (the iLocation variable).

As another example, lets say the player wanted to drop the item "bag" in the room he was in. The only way I know how to do it now would be something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int iLocation;
string sItem;
string s10 = "ball bat glove bar";
string s11 = "// ... so on so forth for each room;

cin << sItem; //user would input "bag"

FunctionDrop(sItem);

void FunctionDrop(Item)
{
      if (iLocation == 10)
      {
          s10.append " ";
          s10.append Item;
      }
      if (iLocation == 11)
      {
          s11.append " ";
          s11.append Item;
      }
//... for all 40 rooms
} 

as you can see that would be alot of code. But if I can do what I'm talking about it would be reduced to this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int iLocation;
string sItem;
string s10 = "ball bat glove bar";
string s11 = "// ... so on so forth for each room;

cin << sItem; //user would input "bag"'

FunctionDrop(sItem);

void FunctionDrop(Item)
{
      s(iLocation).append " ";
      s(iLocation).append Item;
} 

and that would work for all 40 rooms.

I am really hoping something like this is possible because the code efficiency is sooooo much better than an if statement for each room. Sorry if this is confusing, ask anything that is needed.

Thank you.

Last edited on
Use arays (or any container):
1
2
3
int iSelect = 0;
std::vector<std::string> strings = {"Hello", "Hi"};
int iLength = strings[iSelect].size(); //iLength now equals to 5 
Something like:

iLength = sString(iSelect).length();

I just used parenthesis as an example (im not sure what the syntax would be) but the point is that the program would read that line as "iLength = sString1.length();" getting the "1" from iSelect.

NO!!! I think you would want to check C++ vectors.
http://www.cplusplus.com/reference/vector/vector/
Advantage of vectors over arrays is that, vectors are dynamic(their size can be changed at runtime), whiles arrays are static.

Aceix.
Last edited on
I haven't really worked much with arrays so I will check them out and report back if it worked as intended. Thanks!
Hard to tell from your post how much C++ you know. I'm guessing that you're just getting started.

I think want you want to do in your initial example is to use an array of strings.
1
2
3
  string sStrings[2] = { "hello", "hi" };
...
  iLength = sStrings[iSelect].length();


there is a lot of logic that changes based on the room you are in, and this would really help clean up my code because the only way I know how to do it now is have an if statement for every possible room

Have you learned about structs or classes yet?

Consider using an array of structs (or class instances).
1
2
3
4
struct Room 
{  string name; 
    //  other attributes of the room
} rooms[10][10];

Now you can navigate from room to room simply by changing the subscripts to the rooms array. Your logic checks the attributes of a specific room to determine what to do. You don't have to check which specific room you're in. I've shown rooms to be doubly subscripted (x,y grid), but you can make it singly subscripted if you wish. I think navigation is easier with a 2 dimensional grid.

Each room has a string associated with it that holds the items in the room

You really should use a vector of strings for this rather than parsing apart a string to determine what's in a room.
http://www.cplusplus.com/reference/vector/vector/
The vector can be a member of the above ROOM struct.

Edit: I agree with MiiNiPaa's and Aceix's suggestion to use a vector of strings. I started with an array intentionally to keep things simply before introducing vectors for room inventory.








Last edited on
More food for thought:

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
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <map>
#include <vector>
#include <string>

std::map<unsigned, std::vector<std::string>> rooms=
{
    { 1, { "a pebble", "a boulder", "a corpse" } },
    { 2, { "a pink elephant", "a ballerina" } },
    { 3, {} },
    { 4, { "the end of the world" } }
};

int main()
{
    const char* prompt = "Which room would you like to visit?\n> ";

    unsigned room_no;
    while (std::cout << prompt && std::cin >> room_no)
    {
        auto it = rooms.find(room_no);

        if ( it == rooms.end() )
        {
            std::cout << "Unable to find the room number \"" << room_no << "\"\n";
            std::cout << "Terminating program.\n";
            return 0;
        }

        if (!it->second.empty())
        {
            std::cout << "Room " << room_no << " contains:\n";

            for (auto& item : it->second)
                std::cout << '\t' << item << '\n';
        }
        else
            std::cout << "Room " << room_no << " appears to be empty.\n";
    }
}


http://ideone.com/UlOWYA
I set it up using an array and it works PERFECTLY. I may try moving to a vector if I see a need to. Thank you all.
Topic archived. No new replies allowed.