Den Andreychuk
Den Andreychuk

Reputation: 478

Delete part of dynamic array

I created an array with the maximum dimension for text input. Now, I want to remove the remaining unnecessary part in order to free the memory. I am not allowed to use std::string, I need to use char[] arrays only.

Also, if you know better way how to use only char and allocate dynamic memory for text input, please help me. I do not know how many characters the user will enter

#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;
}

Upvotes: 0

Views: 136

Answers (2)

Raindrop7
Raindrop7

Reputation: 3911

You can use a temporary dynamic array then copy the part you wanted from the original array then delete the original array then assign the original pointer to the temporary pointer:

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;

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249123

Just use std::string instead of a C array of char. It will be sized automatically according to the input length.

Use the free function std::getline() instead of istream::getline():

string line;
getline(cin, line);

http://en.cppreference.com/w/cpp/string/basic_string/getline

Upvotes: 5

Related Questions