WestonBuckeye
WestonBuckeye

Reputation: 45

Clear a String array C++

I have 3 functions. One that adds content to each array, one that prints all its context and one that clears all the strings of that array. My question is on the definition of the function that clears the string array. My code deletes each array that is added except the original str[i] or str[0](first slot in array, which holds the string added first). What do i need to add? Am i missing something. Id rather clear it all than set each array slot to a NULL or a str[i] == "";

Here is my attempt:

void StringList::clear()
{
    for(int i=0;i<=numberOfStrings;i++)
    {
        for(int j=i;j<=numberOfStrings-1;j++)
        {
            str[j] = str[j+1];

        }

        numberOfStrings--;
    }


    cout<<"All strings cleared"<<endl;
}

The code clears everything but the first added string. Thoughts? Its probably very simple and my brain is not properly working but everything ive searched does not work.

Is there anyway to clear it without a loop? and just using str[numberOfStrings] ?

Upvotes: 0

Views: 16609

Answers (1)

Nikos C.
Nikos C.

Reputation: 51840

std::string has a clear() function, so that's all you need to call on each element, except the first one:

void StringList::clear()
{
    // Start from 1 so that we won't clear the first string.
    for(int i = 1; i <= numberOfStrings; i++) {
            str[i].clear();
    }
    cout << "All strings cleared" << endl;
}

Upvotes: 2

Related Questions