首页 > 解决方案 > 解析字符串并将其存储在 struct c++ 中

问题描述

我们得到一个 txt 文件,其中包含:“6=3+3”,我想将字符串解析为两个:“6=”和“3+3”。之后,我想将所有内容保存在结构中,而不是数组中,而是结构中。任何想法?

标签: c++stringvisual-studio

解决方案


下面的程序显示了如何分离 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;
}


程序的输出可以在这里看到


推荐阅读