Search code examples
c++strip

c++ parsing string with format


i'm busy for a game for which i must parse a .txt file each row contains a format like this [goblin;2;30x1;1-5;20;5]

the values are as follows:

  • name
  • level
  • attack (before the x the percentage of success, behind the x the amount of attacks in a single turn)
  • damage (the minimum and maximum possible damage)
  • defence (percentage a succesfull attack is still denied)
  • hp

my current code is this:

    std::stringstream sstream(monsterLine);

    // Name is until the first comma.
    std::getline(sstream, monster.name, ';');

    // Then its spaces seperating the values.
    sstream >> monster.level;
    sstream >> monster.attackPoints;
    sstream >> monster.damagePoints;
    sstream >> monster.defensePoints;
    sstream >> monster.lifePoints;

this however only works if i format a string like goblin;2 30x1 1-5 20 5 how can i make it work with the above format?

Specific: how can i check if the current line is placed within [...] and strip them. how can i split the values by ; instead of (whitespace)


Solution

  • getline can be used for tokenization of a string.

    if( (monsterLine.length() > 2) && 
        (monsterLine[0] == '[') && 
        (monsterLine[monsterLine.length() - 1] == ']') )
        {
            std::string szNewMonsterLine = monsterLine.substr(1, monsterLine.length() - 2);
            std::stringstream ss(szNewMonsterLine);
    
            if(getline(ss, monster.name, ';'))
            {   
                //some problem fetching data            
            }
            if(getline(ss, monster.level, ';'))
            {   
                //some problem fetching data            
            }
            if(getline(ss, monster.attackPoints, ';'))
            {   
                //some problem fetching data            
            }
            ...
            ...
            if(getline(ss, monster.lifePoints, ';'))
            {   
                //some problem fetching data
            }   
        }