从字符串转换为字符数组 [英] convert from string to character array
问题描述
我正在从用户那里获取字符串"str".
假设用户输入了str = 123456789
我想将这些数字放在字符数组"ch1"中,而无需预定义char数组.
因此,"ch1"字符应自动具有9的大小,并且ch1 [0] = 1和ch1 [1] = 2等,依此类推....
I am taking in as a string "str" from the user.
Let suppose user entered str=123456789
I want put that numbers in character array "ch1" without predefining the char array.
so that "ch1" character should have the size 9 automatically and ch1[0]=1 and ch1[1]=2 and so on....
推荐答案
您可以使用 c_str [
如果您不需要数组具有预定义的大小,那么您应该动态分配它(记住不再需要它时,请记住删除它),例如,假设str
是std::string
的实例,我们有:
If you don''t want an array with predefined size then you should allocate it dynamically (and remember to delete it when is no longer needed), for instance, assumingstr
is an instance ofstd::string
, we have:
char * ch1; ch1 = new char[str.size()+1]; // +1 makes room for string terminator strcpy(ch1, str.c_str()); //... delete [] ch1;
如果您想做类似
的事情
If you would like to do something like
std::string str = !23456789"; // This is invalid... char ch1[] = str; // None of the alternative below are valid. //char ch1[str.size()] = str; //char ch1[] = str.c_str(); //char ch1[str.size()] = str.c_str();
在C ++中,您不能做类似的事情. C样式数组必须具有在编译时确定的大小,并且无法通过代码中定义的C样式字符串以外的其他字符串初始化此类数组.
如果您需要修改内容,这是一个更好的选择.如果不是,则只需使用字符串运算符[]或c_str()的结果.
In C++, you cannot do something like that. C style array must have a size determined at compile time and there is no way to initialise such an array from a string other than a C-style string defined in code.
Here is a much better alternative if you need to modify the content. If not, then simply use string operator [] or the result of c_str().
std::string str = "123456789"; std::vector<char> ch1(str.begin(), str.end()); // You can know use ch1 almost like an array...
这篇关于从字符串转换为字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!