How to automatically create variables???

HI everyone,

I am trying to create a set of tasks that will loop according to the number of times the user has specified with different sets of variables.

However, I am wondering if there is a way to automatically define "n" sets of variables, without having to pre-define it at the start.

For this simple example,

1) Start
2) No. of land farmer has: nOofland = 5 (cin from user)
3) Lenght of land 1 (m): lengthofland1 = 10 (cin from user)
4) Width of land 1 (m) widthofland1 = 15 (cin from user)
5) nOofland--
6) if nOofLand != 0, loop back to step 3 and asks for details for next plot of land // and at this step I would like to automatically create variables "lengthofland2" and "widthofland2", "lengthofland3" and "widthofland3" and so on... until 5 sets of data is entered.

Could someone please provide the best solution please?

Thank you very much in advance!!!

Cheers

Beginners Jawsh
You need to use an array (or, better yet, a vector).

See: http://cplusplus.com/reference/stl/vector/

Arrays are useful when you know the amount of objects at compile time. http://www.cplusplus.com/doc/tutorial/arrays/
If you know the amount of objects at run time you can use a vector http://www.cplusplus.com/reference/stl/vector/
If you want the user to keep entering stuff without saying how many objects are needed a list may be more appropriate http://www.cplusplus.com/reference/stl/list/
A sample done using vector method.

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
#include <iostream>
#include <vector>

struct Land
{
	int length, width;
	Land(int l_, int w_)
	{
		length = l_;
		width = w_;
	}
};

void main()
{
	int numLands, temp_length, temp_width; //variables to store user inputs
	std::vector<Land> LandList; //list of Lands

	std::cout<<"Enter Number of Lands: ";
	std::cin>>numLands; //get number of lands

	for(int i=0;i<numLands;i++) //loop according to how many lands you have
	{
		std::cout<<"Enter Length of Land "<<(i+1)<<": ";
		std::cin>>temp_length; //get length
		std::cout<<"Enter Width of Land "<<(i+1)<<": ";
		std::cin>>temp_width; //get width
		LandList.push_back(Land(temp_length, temp_width)); //push back the current land
	}

	std::cout<<"\nNumber of Lands: "<<LandList.size()<<std::endl;
	for(int i=0;i<LandList.size();i++)
		std::cout<<"Land "<<(i+1)<<" : "<<LandList.at(i).length<<" "<<LandList.at(i).width<<std::endl;

	system("pause");
}
That's very very helpful guys, especially Ultima thank you very much for preparing the code.

Very much appreciated.

However, is it possible to create a "new" variable say lengthofland2, widthofland2, lengthofland3 and so on....

Now I guess I would have to read into vectors.

But quick question out of this topic, is there a command for C++ to read in a matrix of values? is it arrays?

Thank you

Jawsh
Last edited on
However, is it possible to create a "new" variable say lengthofland2, widthofland2, lengthofland3 and so on....


Create brand new variables with brand new names at runtime that you never typed into the code? The short answer is "no".
But quick question out of this topic, is there a command for C++ to read in a matrix of values? is it arrays?


"Arrays" isn't a command, but they can be used for this purpose if they are inside of a for loop. Something like this is very useful:
1
2
3
4
for(int i = 0; i < sizeof(matrix); ++i) /* matrix in this example is a place holder for what ever you use*/
{
   MyArray[i] = Next_Item_In_Matrix; /*More Place Holders*/
}


Moschops is right about creating variables with new names, afterall how would you even address them inside of your code if you don't know what they are called or what they hold? This is because after the program builds and translates you C++ code, those names don't exist anymore, they are replaced with addresses that have less then helpful hexadecimal labels. So why would your compiler even want to create them at run time?

Vectors are REALLY cool IMO, they are worth any minor pains you may go through while learning them.
Ok, right, I got it! What you didnt define will not be built at the output.

Next, I will definitely spend some time looking into vectors.

Cheers

Thanks!

Jawsh
Ah... Not quite. You wrote "What you didnt define will not be built at the output." This still isn't technically correct and I'm only being this pedantic because I know how hard it is to "unlearn" stuff in this language.

A better way to put it is that once the program is built, the names that you gave to the variables don't exist anymore.
Cheers thanks for the tip!

Yea absolutely its quite hard to "unlearn" stuffs once you get your mind fix on a perspective.
for(int i = 0; i < sizeof(matrix); ++i)

This won't work like you expect.

It should be:
for(int i = 0; i < sizeof(matrix)/sizeof(matrix[0]); ++i)
You can make an arraysize function like this:

source: http://www.cplusplus.com/forum/general/33669/#msg181155
1
2
3
4
5
template <typename T, unsigned S>
size_t arraysize(const T& array[S])
{
	return (sizeof(array) / sizeof(array[0]));
}


firedraco's code will only work on arrays whose size is known at compile time. The above function also only works on arrays whose size is known, but it throws an error when the size is not known, whereas firedraco's does not (meaning that you can't rely on it).

Example:
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
#include <iostream>

template <typename T, unsigned S>
size_t arraysize(const T(& array)[S])
{
	return (sizeof(array) / sizeof(array[0]));
}

int main()
{
	/*
	 * These arrays have sizes known at compile time
	 */
	int array1[10] = {0};
	int array2[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

	/*
	 * These do not
	 */
	const char* array3 = "0123456789";
	char* array4 = new char[24];

	std::cout << arraysize(array1) << "\n"
		  << arraysize(array2) << "\n"
	//	  << arraysize(array3) << "\n"	// no matching function for call to arraysize(const char*&)
	//	  << arraysize(array4)		// ditto
		  << std::endl;

	return 0;
}
Vectors are the better solution anyway.
@chrisname: The actual arraysize function is this:

1
2
3
4
5
template <typename T, unsigned S>
unsigned arraysize(const T (&array)[S]) // the parenthesis here aren't for show
{
    return S;  // no need for sizeof nonsense
}
Topic archived. No new replies allowed.