首页 > 解决方案 > Parse txt - 搜索字符串,如果从下面的行中找到解析数字

问题描述

我有点失落。尝试构建一个搜索特定文本的解析器,如果找到,输出下面的数字。

这是我的 Sample.txt

#BTC/USDT

Client: Binance Futures
Trade Type: Regular (LONG)
Leverage: Isolated (10.0X)

Entry Zone:
19000 - 18980

Take-Profit Targets:
1) 19195 - 20%
2) 19365 - 20%
3) 19580 - 20%
4) 19805 - 20%
5) 20000 - 20%

Stop Targets:
1) 18600 - 100.0%

到目前为止,这是我的超级基本代码:

#include <vector>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

std::string coinpair = ""; // wip
std::string entry = "Entry Zone:";
std::string taprof = "Take-Profit Targets";
std::string stoploss = "Stop Targets";
std::string leaverage = ""; // wip


int main(int argc, char* argv[])
{
    std::fstream myfile("C:\\Projects\\Sample.txt", std::ios_base::in);

    std::string file_contents;

    while (std::getline(myfile, entry))
    {
        file_contents += entry;
        file_contents.push_back('\n');
        cout << entry << ' ';
    }

    getchar();

    return 0;
}

现在我有点太愚蠢了,无法完全按照我的意愿去做,因为它解析了完整的 txt。

我需要的是:搜索入口区:并从下面的新行中解析数字。我希望有人能指出我正确的方向。

标签: c++parsingtexttext-parsing

解决方案


我假设您可以阅读并识别该特定行。
我假设您可以解析一个部分中的行。
这些很容易解析。您可以使用http://www.cplusplus.com/reference/string/string/find_first_of/来定位冒号。

显然问题是什么时候做什么。考虑一个简单的状态机。https://en.wikipedia.org/wiki/Finite-state_machine

当您阅读一行时,您要么正在寻找下一部分开始,要么正在阅读特定部分的行。因此,您只需要一个状态变量来记住您当前正在做什么。

这是一个简单的状态机实现,没有解析细节:

#include <iostream>
#include <fstream>
#include <string>

enum state { top_level, section_level };

std::string parse_section_name(const std::string& line) {
    // if this line starts a section, return the section name
    // returning a non-empty string will change state to "section_level"
    return line;
}

bool parse_entry(const std::string& section, const std::string& line) {
    // return true if this was a valid data line in the section
    // returning false will change state to "top_level"
    return (line.size());
}

int main(int argc, char* argv[])
{
    std::fstream myfile("C:\\Projects\\Sample.txt", std::ios_base::in);

    state current_state = top_level;
    std::string line;
    std::string section_name;
    while (std::getline(myfile, line))
    {
        std::cout << line << std::endl;
        switch (current_state) {
        case top_level:
            section_name = parse_section_name(line);
            if (section_name.size())
                current_state = section_level;
            break;

        case section_level:
            if (!parse_entry(section_name, line))
                current_state = top_level;
            break;
        }
    }
    return 0;
}

推荐阅读