我创建了一个具有文本输入最大尺寸的数组.现在,我想删除剩余的不必要的部分,以释放内存.我不允许使用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;
}
Run Code Online (Sandbox Code Playgroud)
只需使用std :: string而不是C数组的char.它将根据输入长度自动调整大小.
使用免费功能std::getline()而不是istream::getline():
string line;
getline(cin, line);
Run Code Online (Sandbox Code Playgroud)
http://en.cppreference.com/w/cpp/string/basic_string/getline
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |