I am relatively new to C++. I would appreciate if you guys could help me out.
Fundamentally, I am trying to bring a large number of equations from Mathematica into c++. I have used some string functions in mathematica to convert everything into a C++ format. But I am stuck at importing them into C++. I could bring them as a string into a matrix. But I am clueless on how to make these meaningful equations.
let me put it in a simple way.I have a text file with contents:
a+b;
x+y;
a-b;
x-y;
I have a C++ program with a,b,x,y defined as float variables and they have been assigned values:
float a,b,x,y;
a=1;
b=2;
x=3;
y=4;
I used getline() to read these 4 lines from the text file, as strings into a matrix(vector of vectors), defined as RSS. So what I need to do is:
RSS[1][1]=a+b;
RSS[1][2]=x+y;
RSS[2][1]=a-b;
RSS[2][2]=x-y;
But I need them (a,b,x,y) as variables. Is there a way to do it? Or if there are any other better approaches you can recommend? Any help would be much appreciated.
#include <iostream>
#include <string>
#include <cmath>
// define the variables a, b, x, y
constdouble a = 1.2 ;
constdouble b = 2.3 ;
constdouble x = 3.4 ;
constdouble y = 4.5 ;
// given a variable name as a char, return its value
// for instance, if var is 'x', return the value of x
double value_of( char var ) // get the value of a variable
{
switch(var)
{
case'a' : return a ;
case'b' : return b ;
case'x' : return x ;
case'y' : return y ;
// http://en.cppreference.com/w/cpp/numeric/math/NANdefault : return NAN ; // invalid variable name; decide what you want to do here
}
}
// evaluate expression of the form var1 op var2 eg "a+b"
double evaluate( std::string expression )
{
if( expression.size() != 3 ) return NAN ; // badly formed expression
constdouble first = value_of( expression[0] ) ;
constchar oper = expression[1] ;
constdouble second = value_of( expression[2] ) ;
switch(oper)
{
case'+' : return first + second ;
case'-' : return first - second ;
case'*' : return first * second ;
case'/' : return first / second ;
default: return NAN ; // invalid operation name; decide what you want to do here
}
}
std::string clean( std::string expr ) // remove whitespace, convert to lower case
{
std::string clean_str ;
for( char c : expr ) // for each character in expr http://www.stroustrup.com/C++11FAQ.html#forif( !std::isspace(c) ) // if it is not a white space http://en.cppreference.com/w/cpp/string/byte/isspace
clean_str += c ; // add it to the clean string
return clean_str ;
}
int main()
{
std::string input = " b + x " ;
// read input from the file
std::cout << "a==" << a << ", b==" << b << ", x==" << x << ", y==" << y << '\n' ;
const std::string expression = clean(input) ;
std::cout << expression << " == " << evaluate( expression ) << '\n' ;
}