1 min
In order for my game to retrive specific words from the player’s input this function were created to handle this.
The getWord function has two arguments:
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.
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;
}
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
Subscribe to this blog via RSS.
C++ 30
Directx12 11
Mario kart 11
Commercial games development 15
Unity 15
Low-level programming (19) C++ (30) Text based adventure (5) Ex-machina (9) Game engine programming (11) Directx12 (11) Mario kart (11) Land of gold (5) Audio visual production (1) Commercial games development (15) Unity (15) Don't walk by (15)