[英]String to char array in c++
I was making a simple program in c++ to convert a string to a char array and then print it out.我在 c++ 中制作了一个简单的程序,将字符串转换为 char 数组,然后将其打印出来。 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.我得到的错误是“表达式必须有一个常数值”,我不知道为什么。
In char char_array[lenght + 1];
在char char_array[lenght + 1];
, lenght + 1
is not a compile-time constant. , lenght + 1
不是编译时常量。 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.由于直到运行时才知道length
的值,所以在这种情况下,您需要动态分配 memory。 For example:例如:
char* char_array = new char[lenght + 1];
Don't forget to delete the array when you are done:完成后不要忘记删除数组:
delete[] char_array;
You can use:您可以使用:
char* c = _strdup(UserImput.c_str());
But I wonder - why?但我想知道 - 为什么? Just to output it to cout
?只是为了 output 它来cout
吗? Then you can do:然后你可以这样做:
cout << UserImput.c_str();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.