How can I do this?

I have this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string>
#include <iostream>

string square1;

void test(int number)
{
   square+number = "lol";
}

int main(int argc, char* args[])
{
  test(1);
}


Please focus on this piece of code:
square+number = "lol";

I want that to be that the same as doing:
square1 = "lol";

In PHP you would use the "eval()" function:
eval("$square".$number." = 'lol';");

How would you do it in C++?
I'm not familiar with php, so I do not quite understand what that piece of code does, but here goes.

If what you want is to have 50 square variables, and be able to choose which specific one by using a parameter number, you would need to use an array. You would declare it as string square[50];, and you can access the 50 variables by it's position, 0-49.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string>
#include <iostream>

string square[20];

void test(int number)
{
   square[number] = "lol";
}

int main(int argc, char* args[])
{
  test(1);
}


If I misunderstood what it is you were trying to do, please let me know in more detail.
Ah yes, I forgot about arrays. Thank you very much!

One last thing:
When should I use a void and int? Because I think you can use both when creating a function.
A function should return void when it doesn't return anything, and should use an int when it returns an int.

"return" values are generally output of the function. They allow you to assign function results to a variable:

1
2
3
4
5
6
7
8
9
10
11
12
13
int func_that_doubles(int dbl)
{
  return dbl * 2; // the value we're returning
}

int main()
{
  // see how we're assigning var to a function call.
  //  this means var will get assigned to whatever the function returns.
  int var = func_that_doubles( 5 );

  cout << var;  // so now, var is 10.  this prints "10"
}


Since your 'test' function doesn't really have any of this kind of output, it makes sense for it to be a void.
Topic archived. No new replies allowed.