c ++如何读取名称以及随后的信息

时间:2018-12-06 22:02:46

标签: c++

我正在尝试读取以下格式的文件:

"Champion: "aatrox
  Aatrox heals for 20 / 22.5 / 25 / 27.5 / 30% of the premitigation-physical damage he deals, with a 15% effectiveness against non-champions.
  Additionally, Aatrox stores a Umbral Dash charge every 24 / 20 / 16 / 12 / 8 seconds, up to 2 stored at once.
  Aatrox dashes in the target direction, gaining 15 / 25 / 35 / 45 / 55 bonus attack damage for 1.5 seconds.
  Umbral Dash can be cast during his other spellcasts without interrupting them.
"the end"
"Champion: "ahri
  Ahri blows a kiss that deals 60 / 90 / 120 / 150 / 180 (+40% of ability power) magic damage to an enemy and charms it, causing them to walk harmlessly towards her for 1.4 / 1.55 / 1.7 / 1.85 / 2 seconds.
  When Charm damages a champion, Ahri's abilities deal 20% more damage to them for 5 seconds.
"the end"

我需要能够读取冠军名称,将其存储在字符串中,然后读取后面的信息并将其存储在字符串中

1 个答案:

答案 0 :(得分:0)

我更喜欢正则表达式,因为它非常灵活。另外,如果您使用boost,则可以按照Using a regex_iterator on an istream

的要求通过文件直接运行正则表达式

下面是您可以轻松实现的示例代码

#include <iostream>
#include <fstream>
#include <regex>

int main(int argc, char **argv) {
    const std::regex characterPattern(R"-(("Champion:\s*")(\w+))-");

    std::ifstream charsfile;
    charsfile.exceptions (std::ifstream::failbit | std::ifstream::badbit );
    charsfile.open("/home/abdurrahim/projects/testregex/test.txt");

    const std::string charstext((std::istreambuf_iterator<char>(charsfile)),
                 std::istreambuf_iterator<char>());

    charsfile.close();

    for(std::sregex_iterator i(charstext.begin(), charstext.end(), characterPattern); i != std::sregex_iterator(); ++i)
    {
        std::smatch m = *i;

        std::cout << m[1] << " found at " << m.position() << " with name '"  << m[2] << "'" << std::endl;
    }

    return 0;
}

我使用在线正则表达式测试器来寻找这种正则表达式模式