[英]Delete part of dynamic array
我創建了一個具有最大尺寸的文本輸入數組。 現在,我想刪除剩余的不必要部分以釋放內存。 我不允許使用std::string
,我只需要使用char[]
數組。
另外,如果您知道更好的方法,如何僅使用char並為文本輸入分配動態內存,請幫助我。 我不知道用戶將輸入多少個字符
#include <iostream>
using namespace std;
int main()
{
char *text = new char[256];
cout << "Input text: ";
cin.getline(text,256,'\n');
while (cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max, '\n');
cout << "Input text: ";
cin.getline(text,256,'\n'); //need to delete part after '\n';
}
return 0;
}
只需使用std :: string而不是char的C數組即可。 它將根據輸入長度自動調整大小。
使用免費函數std::getline()
代替istream::getline()
:
string line;
getline(cin, line);
http://en.cppreference.com/w/cpp/string/basic_string/getline
您可以使用臨時動態數組,然后從原始數組中復制所需的部分,然后刪除原始數組,然后將原始指針分配給臨時指針:
char* szTxt = new char[256];
std::cin.getline(szTxt, 256, '\n');
std::cout << szTxt << std::endl;
const int size = strlen(szTxt);
char* szTmp = new char[size + 1];
strncpy(szTmp, szTxt, size);
szTmp[size] = '\0';
delete[] szTxt;
szTxt = szTmp;
std::cout << szTxt << std::endl;
std::cout << "Size: " << size << std::endl;
delete[] szTxt;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.