we are given a txt file with :"6=3 3" and i want to parse the string in two like:"6=" and "3 3". afterwards I want to save everything in a struct not array but struct. any idea?
CodePudding user response:
You could make 2 string members for the struct, one RHS and one LHS. Then you can make a member function which takes a string argument(The equation to be parsed) and either you could use a for loop which iterates through the string checking for an equal sign and once it finds it, it then stores the iterated part to the LHS and continues the iterator and stores the rest in RHS.
Or
You can parse the string to a stringstream like this:
std::stringstream stream;
stream << equation;
And then use std::getline with a delimiter of "=" and seperate the string like that way. There are way more ways to do it than this. Try doing it yourself!
CodePudding user response:
The below program shows how you can separate out the LHS(left hand side) and RHS(right hand side) and store it in a struct object.
#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;
}
The output of the program can be seen here