Reputation: 35
I was making a simple program in c++ to convert a string to a char array and then print it out. My code is:
string UserImput;
int lenght;
void Test()
{
getline(cin, UserImput);
lenght = UserImput.size();
char char_array[lenght + 1];
copy(UserImput.begin(), UserImput.end(), char_array);
cout << char_array;
}
The error I am getting is "expression must have a costant value" and I do not know why.
Upvotes: 1
Views: 265
Reputation: 13547
In char char_array[lenght + 1];
, lenght + 1
is not a compile-time constant. The size of an array must be known at compile-time. Since the value of length
is not known until runtime, you will need to allocate memory dynamically in this situation. For example:
char* char_array = new char[lenght + 1];
Don't forget to delete the array when you are done:
delete[] char_array;
Upvotes: 5
Reputation: 11311
You can use:
char* c = _strdup(UserImput.c_str());
But I wonder - why? Just to output it to cout
? Then you can do:
cout << UserImput.c_str();
Upvotes: 0