0

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] ?

5
  • What do you think str[j]== str[j+1]; does? Hint: == is not =. Commented Jun 8, 2013 at 4:36
  • @Patashu Didnt notice that! Fixed it thanks! But it still doesnt fix my problem. Commented Jun 8, 2013 at 4:38
  • I think you'll need to add more code, like the declaration of StringList. Commented Jun 8, 2013 at 4:44
  • I have all that code seperate already written. I just need help with this function. @RetiredNinja Commented Jun 8, 2013 at 4:45
  • Without knowing what str is declared as it's nearly impossible to tell what you want. Give us enough code to help you. Commented Jun 8, 2013 at 4:48

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Clears it but it just makes them NULL or "". I want them deleted completely from scratch. Ill accept it anyway! Thanks
@user2465567 If they're not pointers that were previously allocated with new, how would you expect to delete them? The only way you can do that is by deleting the array itself and reallocate it with a size of 1. Then, every time you need to add a new element, you need to delete the array again and allocate it with a size + 1. Can you imagine the horror?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.