开发者

Using a for statement to create variables from array

I have a set of numbers that I need to pass from a function to a few other functions before it is actually used. I figured an array is a good way to do this, however I can't remember how to do what I want to do. The code looks like this

int set1; // variables that hold settings
int set2;
int set3;
cout << "Setting 1";
cin >> set1;
cout << "Setting 2";
cin >> set2;
cout << "Setting 3";
cin >> set3;
int settings[3] = {set1, set2, set3}; //array that holds variables

so that is how the array is created.

However what I am hoping is to be able to do something like this, I know some languages can ( I am pretty sure), but I don't know if C++ can, or what this method is even called (so I can't google it)

开发者_Go百科
int setting0;
int setting1;
int setting2;
    for(int i=0; i<3; i++)
    {
          setting+i = setting[i]; // should set setting0 = setting[0]; etc
    }

Am I going about this the wrong way?


There's no way to do this without initially using an array (i.e., int set[3]), or doing something more complicated than your first example.

Of course, you can rewrite your code, such as

int settings[3];
for (int i = 0; i < 3; ++i)
{
    cout << "Setting " << i+1;
    cin >> settings[i];
}


If the functions you're calling need to change the array content, Change your array decl to this:

int *(settings[3]) = {&set1, &set2, &set3}; //array that holds pointers to variables

Then change your loop to:

for(int i=0; i<3; i++)
{
 *(settings[i]) = setting[i]; // should set set1 = setting[0]; etc
}

Not sure if I understood your question quite right...


You can't reference variables from a name computed at runtime like that in C++. Your options are either to pass the array itself directly to the function in question (this is probably the best approach) or to bind the variables manually at compile time:

// NOTE - this is ALMOST ALWAYS not the right thing to do!
int setting0 = setting[0];
int setting1 = setting[1];
int setting2 = setting[2];


I think this is the wrong approach. If you are passing an array, why not use the values in the array?

Like, instead of

printf("Hello %s",setting3);

do

printf("Hello %s",setting[3]);

or if you want to be fancy and use an associative array

printf("Hello %s",setting['first_name']);


Sorry, this was a dumb question, I need to take a break. What I will do is set all the cin >> setting[0]; etc. I don't know what I was thinking, can I unask, lol.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜