如何将字符串保存到动态char数组中

时间:2019-01-26 03:46:47

标签: c++

  • 该数组应该是动态的,但它是固定的。
  • 打印数组没有任何效果。

我正在尝试创建动态char数组,从用户那里获取字符串行,将char的行字符串char保存到数组中。

#include <iostream>
#include <string>
using namespace std;
int main()
{
char* lenptr = NULL;        // declare a pointer initialized with null
int leng, arrsz;
string mystr;
cout << "enter a string: ";
getline(cin, mystr);        // input a line of string
leng = mystr.length();      // get length of string
cout << "string length: " << leng << endl;
lenptr = new char[leng+1];      // declare a dynamic char array with length+1
for (int i = 0; i < leng; i++)
{
    lenptr[i]=mystr[i];     // fill array with saved string
}
lenptr[leng] = '\0';        // save '\0' in last array cell
arrsz = sizeof(lenptr);     // get size of array
cout << "size of array after saving " << leng << " chars: " << arrsz << endl;
cout << "string in array: ";
for (int j = 0; j < leng; j++)      // print array
{
    lenptr[j];
}
cout << endl;
// delete pointer
delete[] lenptr;
lenptr = NULL;  
system("pause");        // pause system
return 0;
}

输入字符串:helloworld 字符串长度:10 保存10个字符后的数组大小:8 数组中的字符串: 按任意键继续 。 。

1 个答案:

答案 0 :(得分:0)

You can't get the size of an array allocated with new[]。尽管建议使用std::string,但是如果绝对必须将字符串存储在数据结构中,则向量将是更可行的选择。

无论如何,您的程序不会打印数组的字符,因为您在for循环中忘记了std::cout

for (int j = 0; j < leng; j++)      // print array
{
    cout<<lenptr[j];
}

并使用前面定义的leng变量来实际打印出数组的大小:

cout << "size of array after saving " << leng << " chars: " << leng + 1 << endl;