011235813
011235813

Reputation: 35

String changes after function call

I'm probably making a very obvious mistake, but I just can't see it and I'm hoping somebody can help me.

I want to add 2 strings into a vector of pairs in my C++ program. The container looks like vector< pair < word , type > > vec. Where the word can be anything and the type is a noun, adjective, verb, and so forth. For example < Hogwarts , noun>, < Hungry, adjective>, and so on.

Here's where I add the words to the word bank. FileStrings is just another container created from File I/O. Everything is fine here.

for(unsigned int i = 0; i < fileStrings.size(); ++i)
{
    cout << "Adding " << fileStrings[i] << ", " << fileStrings[i + 1] << endl;
    theWordBank.addWord(fileStrings[i], fileStrings[++i]);
}

Here's where I get lost. When newWord is printed out it is exactly the same as newType. I can't make sense of it and I don't understand how newWord lost its value from the code snippet above.

void addWord(const string& newWord, const string& newType)
{
    mWords.push_back(make_pair(newWord, newType));
    std::cout << "newWord " << newWord << ", " << newType << std::endl;
}

Once again, the result should be something like < Hogwarts, noun>, but instead I get < noun, noun> for everything in the mWords vector of pairs. I don't think it even has anything with mWords. Is my assignment list for the addWord function doing something wrong?

Upvotes: 1

Views: 71

Answers (2)

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

There are further issues with your code. You are accessing an element out of bounds of the vector in your cout.

for(unsigned int i = 0; i < fileStrings.size(); ++i)
{
    cout << "Adding " << fileStrings[i] << ", " << fileStrings[i + 1] << endl;

Assume that fileStrings contains 1 item. The fileStrings[i+1] would attempt to access fileStrings[1] ,which is an out-of-bounds access.

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 993413

This is likely your problem:

theWordBank.addWord(fileStrings[i], fileStrings[++i]);

It is undefined behaviour to use i more than once in an expression where you also use ++i (or other increment/decrement operator). Do this instead:

for(unsigned int i = 0; i < fileStrings.size(); i += 2)
    theWordBank.addWord(fileStrings[i], fileStrings[i + 1]);
}

There will be absolutely no discernible difference in performance.

Upvotes: 5

Related Questions