Trying to have user determine the size of an array

I am having difficulties with determining the size of an array. I want the user to determine the size but I can't seem to get the code right.

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
41
  #include<iostream>
#include<string>
using namespace std;

void printArray(string ClassList[ ], int StudentSize);

int main()
{
	//Declare variables
	int numStudents;

	//Have user determine size of array by entering the number of students in class
	cout << "Enter the number of students in your class: ";
	cin >> numStudents;

	//declare array 
	string Roster[numStudents];

	//Enter the names of each of your students
	cout << "Enter the names of each of your students.\n";
	for(int x = 0; x < numStudents; x +=1)
	{
		cin >> Roster [x];
	}

	//Display the Class list and number of students
	printArray(Roster, numStudents);

	return 0;
}

//Function Definition
void printArray(string ClassList[ ], int StudentSize)
{
for(int x = 0; x < StudentSize; x +=1)
{
	cout << "The names of your students are: \n";
	cout << ClassList [x] << endl;
}
cout << "You have " << StudentSize << "students. \n";
}
Default c arrays like you're using cannot be created with variables. You have to either dynamically allocate them, or use vectors.
string Roster[numStudents];
This is not valid in C++ (though I think it is in C99).

If you want the user to determine the size of the array, either use new (not recommended), or std::vector (preferred).

Using new:

1
2
3
std::string* Roster = new std::string[numStudents];
//Do whatever you need with this...
delete[] Roster; //Clean up your memory 


Using std::vector

 
std::vector<std::string> Roster(numStudents);


A vector is just an array which dynamically resizes when it needs to.
Okay. I do not know how to use vectors yet. For now, I will just determine the size of the array. Thanks for your help.
Vectors aren't difficult at all. In fact, you can use them almost identically to arrays.

I recommend using a vector. It's much safer, easier, serves your needs perfectly, and is more proper C++.
Topic archived. No new replies allowed.