Text Based Adventure String Handling

Text Based Adventure String Handling

Nov 5, 2018. | By: Evan Diamond
1 min

In order for my game to retrive specific words from the player’s input this function were created to handle this.

getWord

The getWord function has two arguments:

  1. The string with the word in.
  2. The position of the word within the string.

The function loops through the string each letter at a time. If the letter is a space then it checks to see if the number of counted spaces (space_count) is less then the position of the word -1. If this is true space_count is incremented else the loop ends as the word would’ve been found because it would be that the space in that position is after the word’s position. If the letter isn’t a space and the space_count equals the word’s position -1 then letter appended to a new string. Once the loops ends or is broken this string is returned from the function.

Code

std::string GameScene::getWord(std::string line, int word_pos)
{
    std::string word = "";
    int space_count = 0;
    for (char letter : line)
    {
        if(letter == ' ')
        {
            if(space_count < word_pos - 1)
            {
                ++space_count;
            }
            else
            {
                break;
            }
        }
        else if(space_count == word_pos - 1)
        {
            word += letter;
        }
    }
    return word;
}

Post Mortem

After finishing this project I realised that a function for finding a word within a string is already in the standard library, std::find(). In the furture I will use this function as it will be more robust (my function could break if the word entered wasn’t in the string). Although, it still was usefull to learn how to implement this. [hampden]: https://github.com/jekyll/jekyll

About

Gamers developing new games.

Social Links

Our Bunker

University of the West of England,
Frenchay Campus, Bristol, BS16 1QY,
United Kingdom.