Boolean expression parse and evaluation in C++ - c++

I need to evaluate simple Boolean functions at run time in C++. The functions are read from a file as strings. Is there any library available that I could use for this?
I looked into BuDDy but sounds like it doesn't parse strings.

Use boost library (lexical_cast.hpp)
bool a = boost::lexical_cast<bool>("true"); //true
bool b = boost::lexical_cast<bool>("0"); //false
Or go here num_get facet and stringstream conversion to boolean - fails with initialised boolean?

Related

How to give command line input to this C++ program

I am running a simple program:
#include<iostream>
#include<math.h>
using namespace std;
double fu (double x) {
double func = pow(x,0.5);
return func;
}
int main (int argc, char* argv[]) {
double x = 2;
double func = fu(x);
cout<<"f(x) = "<<func<<endl;
return 0;
}
Here func is a function of which value is calculated at x.
Suppose, I need to use this program from another program or if I want to give a function, such as pow(x,0.5) or sqrt(1+sin(x)) during command line running of this program.
How I can do that? If I do it using argv, then can you suggest how can I convert a string into an expression func (that can be evaluated by C++ compiler)?
Any suggestions?
There's no easy way to automatically evaluate that kind of math expressions from a string in c++ (like you may have experienced with kind of eval() expressions in scripting languages).
C++ is a compiled language, and the compiler can't actually resolve anything to concrete function calls and parameter values at compile time.
You have to parse these strings at runtime, break down the input tokens and parameters, and map the parsing results to concrete function calls of the appropriate <cmath> functions applying the parsed parameter values, from within your program.
That's not trivial, and there are a number of solution approaches available. But these completely depend on the kind of math language you want to parse from the command line arguments.
There is not such thing as 'execute an expression in a string' in standard C++. The reason is because C++ is a compiled language (i.e. the output is binary code that the processor can directly execute without any intermediate interpreter). So it cannot just interpret an expression (or code in general) from a string.
I have an implementation in Snap Websites, there is C++ code:
https://sourceforge.net/p/snapcpp/code/ci/master/tree/snapwebsites/lib/snap_expr.cpp
Go here to find the other files:
https://sourceforge.net/p/snapcpp/code/ci/master/tree/snapwebsites/lib
However, instead of implementing an expression parser and execution environment, you may want to make use of an existing library (mine is an example, obviously, actually I have a tool named snapexpr under snapwebsites/src which will do exactly what you are talking about!) In that case you could also choose a different language. For example, Qt offers QScript:
http://qt-project.org/doc/qt-5/qtscript-index.html
In that case, you have to write JavaScript code, but since JavaScript is relatively close to C++, it may work in your environment.

Ternary operator in bison, avoid both side computation

I have this rule in my grammer for ternary operator:
Int:
Boolean '?' Int ':' Int {if($1==1) $$=$3; else $$=$5;}
| ...
For numbers and expressions this works fine but suppose I have this code when a is integer:
a=5
1==1 ? a++ : a++
cout<<a;// now a==6 is the correct print but I got a==7
Both side of the ':' are computed but I need only one side.
How can i do it in bison?
The only way I see to accomplish what you want while keeping your one-pass interpreter approach would be to have a global flag that controls whether evaluation takes place (while that flag was set to false, the parsing rules would parse normally, but not execute anything, which you'd accomplish by enclosing each action in an if. The rule for the ternary operator could then invoke mid-rule actions or special parsing rules that set this flag according to the condition.
The proper way to solve this is by not executing the program directly in the parser. Instead let the parser build an AST (or some other intermediate representation if you prefer), which you then walk to execute the program in an additional stage.
In that stage you can then easily decide which branch to evaluate after evaluating the condition. The logic for that would look something like this:
class TernaryOperator : public IntExpression {
// ...
public:
int eval() {
if(condition.eval()) {
return then_branch.eval();
} else {
return else_branch.eval();
}
}
}
Of course the above is only an example and might be better written using the visitor pattern instead.

Boolean Not Equal To in Lua programming

How to write if statement in Lua with not equal symbol for boolean variable.
//In Java,
boolean a;
a = false;
if(!a){
//do something
}
-- In Lua I am trying to replicate the same code
local a
a = false
if(~a) then
-- do something
end
But I am getting error. How to write this in Lua ?
Lua uses mostly keywords. Use not a instead of ~a.

using boost string algorithm with MFC CString to check for the end of a string

I need to check whether my CString object in MFC ends with a specific string.
I know that boost::algorithm has many functions meant for string manipulation and that in the header boost/algorithm/string/predicate.hpp could it be used for that purpose.
I usually use this library with std::string. Do you know a convenient way to use this library also with CString?
I know that the library is generic that can be used also with other string libraries used as template arguments, but it is not clear (and whether is possible) to apply this feature to CString.
Can you help me with that in case it is possible?
According to Boost String Algorithms Library, "consult the design chapter to see precise specification of supported string types", which says amongst other things, "first requirement of string-type is that it must [be] accessible using Boost.Range", and note at the bottom the MFC/ATL implementation written by Shunsuke Sogame which should allow you to combine libraries.
Edit: Since you mention regex in the comments below, this is all you really need to do (assuming a unicode build):
CString inputString;
wcmatch matchGroups;
wregex yourRegex(L"^(.*)$"), regex::icase);
if (regex_search(static_cast<LPCWSTR>(inputString), matchGroups, yourRegex))
{
CString firstCapture = matchGroups[1].str().c_str();
}
Note how we reduce the different string types to raw pointers to pass them between libraries. Replace my contrived yourRegex with your requirements, including whether or not you ignore case or are explicit about anchors.
Why don't you save yourself the trouble and just use CStringT::Right?

String to Time Conversion

In C++ is there any way to extract a time from a string?
CString str;
str="17:18:58,9187120";
Is there any utility for converting this string in to a Time variable?
see this question:
Convert a string to a date in C++
The POCO library has a DateTimeParser class which might be helpful:
http://www.appinf.com/docs/poco/Poco.DateTimeParser.html
Not in C++ or its standard library. C++ barely handles its own complexity, it's too much to ask for anything that isn't common to all cultures, platforms, galaxies and vegetables.
For now you can do with Boost's string conversion functions.