I am trying to set up an array of string that’s size and content dependent on the users input. I am getting an error declaring my array, it says the variable for the size is not the right type. I’ve spent a few hours on this just thought I’d ask.
Here’s my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Enter number of names /n";
int a;
cin >> a;
string namesArray[a]; //Error is here.
for( int i=0; i<a; i++) {
string temp;
cin >> temp;
namesArray[i] = temp;
}
for( int j=0; j<a; j++) {
cout << "hello " << namesArray[j] << "/n";
}
return 0;
}
The error is at string namesArray[a];
An array needs to have a compile-time value for its size. Your code wont compile because
ais not a compile-time constant.Better use
std::vector: