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.
2 Answers 2
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;
-
Rather than using
new[]
directly, you should usestd::vector
instead, then you don't have to worry about callingnew[]
/delete[]
manually, eg:std::vector<char> char_array(lenght + 1); std::copy(UserImput.begin(), UserImput.end(), char_array.begin()); std::cout << char_array.data();
Remy Lebeau– Remy Lebeau2020年07月30日 22:17:39 +00:00Commented Jul 30, 2020 at 22:17
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();
-
2Or better,
cout << UserImput;
sinceoperator<<
has an overload forstd::string
Remy Lebeau– Remy Lebeau2020年07月30日 22:16:10 +00:00Commented Jul 30, 2020 at 22:16 -
1Side note: Remember that the buffer returned by
strdup
needs to befree
ed, notdelete
ed.user4581301– user45813012020年07月30日 23:08:12 +00:00Commented Jul 30, 2020 at 23:08
std::string
s already use arrays under the hood. Use.c_str()
go get the pointer to its first element (or.data()
for a writeable pointer).