c++ - 解析字符串并将其存储在 struct c++ 中
问题描述
我们得到一个 txt 文件,其中包含:“6=3+3”,我想将字符串解析为两个:“6=”和“3+3”。之后,我想将所有内容保存在结构中,而不是数组中,而是结构中。任何想法?
解决方案
下面的程序显示了如何分离 LHS(左侧)和 RHS(右侧)并将其存储在结构对象中。
#include <iostream>
#include <sstream>
#include<fstream>
struct Equation
{
std::string lhs, rhs;
};
int main() {
struct Equation equation1;//the lhs and rhs read from the file will be stored into this equation1 object's data member
std::ifstream inFile("input.txt");
if(inFile)
{
getline(inFile, equation1.lhs, '=') ; //store the lhs of line read into data member lhs. Note this will put whatever is on the left hand side of `=` sign. If you want to include `=` then you can add it explicitly to equation.lhs using `equation1.lhs = equation1.lhs + "="`
getline(inFile, equation1.rhs, '\n'); //store the rhs of line read into data member rhs
}
else
{
std::cout<<"file cannot be opened"<<std::endl;
}
inFile.close();
//print out the lhs and rhs
std::cout<<equation1.lhs<<std::endl;
std::cout<<equation1.rhs<<std::endl;
return 0;
}
程序的输出可以在这里看到
推荐阅读
- python-3.x - 从日期范围生成每周开始和结束日期的列表列表
- mysql - 选择重复项会为每个查询提供不同的结果计数
- backbone.js - 使用文本区域中的数据更新 Netsuite 记录中的字段
- python - 我在python中使用串行通信模块..但是接收到的数据不正确..它不稳定并且大部分时间都在变化
- python - 在数据框中的列表中查找元素
- mysql - 如何进行自动 MySQL 数据库备份?
- pointers - 如何计算画布中的鼠标指针位置?
- swift - 带有基本身份验证的 RestApi 问题
- ios - 如何使用 Swift 以编程方式将 BLE 设备(nRF 52840)与 iOS iPhone 配对
- python - 如何在 2 个数据帧的 3 列中找到最接近的值?