【问题标题】:Parse string and store it in struct c++解析字符串并将其存储在 struct c++ 中
【发布时间】:2021-12-12 14:53:18
【问题描述】:
我们得到了一个 txt 文件,其中包含:“6=3+3”,我想将字符串解析为两个:“6=”和“3+3”。
之后,我想将所有内容保存在结构中,而不是数组中,而是结构中。有什么想法吗?
【问题讨论】:
标签:
c++
string
visual-studio
【解决方案1】:
您可以为结构创建 2 个字符串成员,一个 RHS 和一个 LHS。
然后你可以创建一个成员函数,它接受一个字符串参数(要解析的方程),或者你可以使用一个 for 循环来遍历字符串检查等号,一旦找到它,它将迭代的部分存储到LHS 并继续迭代器并将其余部分存储在 RHS 中。
或者
您可以像这样将字符串解析为字符串流:
std::stringstream stream;
stream << equation;
然后使用带有“=”分隔符的 std::getline 并以这种方式分隔字符串。有比这更多的方法来做到这一点。自己试试吧!
【解决方案2】:
below 程序展示了如何分离 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;
}
程序的输出可见here