c++ - 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。
我需要的是:搜索入口区:并从下面的新行中解析数字。我希望有人能指出我正确的方向。
解决方案
我假设您可以阅读并识别该特定行。
我假设您可以解析一个部分中的行。
这些很容易解析。您可以使用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;
}
推荐阅读
- android - JavaScript 接口注入漏洞修复
- python-3.x - 如何解决错误:UnicodeDecodeError:'utf-8'?
- python - 在 Tkinter 的 for 循环中创建暂停
- php - 将注册表单数据提交到数据库 - phpMyAdmin
- r - Web API - 如何在 R 中选择 httr::get() 请求中感兴趣的变量
- sql - 带有 INSERT 的 Oracle SQL 事务
- angular - 当我单击不同组件的按钮时,在不同组件的角度显示模式中?
- python - keras 序列模型中的多个输出
- elementor - 连接到 elementor 小部件?
- python - 如何在 Python 中将 [{'id':1'}] 之类的字符串转换为列表 [{'id':1'}] 数据类型?