Hi,

I start with code:

int main()
{
    Dict d;
    int n;
    std::cin >> n;
    char word[100];
    for (int i = 0; i < n; i++)
    {
        std::cin >> word;
        d.addWord(word);
    }

    d.addWord("dog");
    d.addWord("drog");

....

return 0;
}

I don't know why when I call method addWord manually, i.e. calls d.addWord("dog") or d.addWord("drog") it works good. But when I try to input data during program work (std::cin>>word) it stores only my last put word.

For example if i try to input words: car, train, bus and later words dog and drog are added, program after taking some operations, returns vector of these words, so it should look like :
car, train, bus, dog, drog and I get bus,bus,bus,dog,drog.

Method addWord takes as an argument pointer Word* w (Word is class created by mine). I suppose that I do something wrong on input, because I tested program earlier with fixed data and it worked alright.

I believe it's your class you need to show.
Also might be a silly question but what type of object is Dict?

Is Dict storing just the pointer address passed to it by addWord()? If yes, then that would explain why passing string literals such as "dog" and "cat" works while passing a character array doesn't. Dict needs to duplicate the string within the class so that the class has it's own copy.

For example: Here I'm assuming Word is a char pointer.

Dict::addWord(const char* w)
{
   Word = new strlen(w)+1;
   strcpy(Word,w);
}

Edited 2 Years Ago by Ancient Dragon

Ancient Dragon - you were right. In constructor of class Word I did simple assigment

Word(char* word)
{
    this->word = word;
}

, and I should :

Word(char* word)
{
    this->word = new char[strlen(word) + 1];
    strcpy(this->word,word);
}

Thanks

This question has already been answered. Start a new discussion instead.