Using boost::lexical_cast with arithmetic expressions - c++

I have an input file (ASCII) with arithmetics, e.g.
TEST;0.0;0.0+0.1;0.0+0.2
I can read the string and split it accordingly, so I already have elements of std::string. Now I wanted to use boost::lexical_cast<double> to store it in a double, comparable to an expression like:
double d = boost::lexical_cast<double>("0.0+0.1");
However, Boost throws
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >'
what(): bad lexical cast: source type value could not be interpreted as target
Is there a good way to go, maybe without sscanf? (If sscanf would be capable of doing this at all...)
TIA

boost::lexical_cast is not a parser/calculator. You could use Boost.Spirit to do this. There's an O'Reilley example on how to implement such a calculator, but as you can see it's not straight-forward.
Questions OpenSouce C/C++ Math expression parser Library and Evaluating arithmetic expressions in C++ might be good starting points if you want to implement a simple parser.

A solution could be splitting the strings again, if there's an arithmetic operator in the string, do the cast for both substrings and then do the arithemtic operation.
I don't think boost::lexical_cast or anything similar does this or is intended to do this.

Related

Are there any functions in the C++ library that converts a string into an arithmetic operation?

I understand that the stoi() function might suit the needs of only an integer value, however I need to convert the following string into an actual arithmetic operation. For example:
"3 + 7 * 4 - 2" into 3 + 7 * 4 - 2
where if I had to assign that to a variable the result will be 29.
In short : No.
How to handle this truly depends on how the string was created in the first place.
Is this some user providing some simple input on stdin and you catch it with std::cin ?
If it's really a simple expression (no parenthesis etc.), you could read from stdin an int, a char, an int, a char, an int etc... and just parse the char as the operator.
I've come accross the Shunting-Yard Algorithm when I had similar a issue and it seemed to be quite what I wanted.
You could also implement some grammar. It's really rewarding when it works but this is a lot of work and overkill. See parsing math expression in c++. You'll have way better comments than mine there with code examples.

How to test if a string is a valid C++(ish) expression?

I am writing a program in C++ that needs to be able to test if a string (probably std::string) is a valid C++ expression. Variables can be checked if they have been declared (bool variableDeclared(std::string identifier)) and their type can also be checked (std::string variableType(std::string identifier)). The variableType function returns a string based on how it would be declared in C++ ("bool", "double", "char", etc).
The expression doesn't need to be evaluated but only tested to see if it is valid. The function only needs to support character literals, string literals, number literals, brackets, simple operators (+, -, *, /, ! (logic not), &&, ||, >, <, ==), and variables of type double, std::string (no function calls needed), bool and char. It is also not required to support string concatenation.
The desired result would be a function that is something like bool validExpression(std::string expression). It is also preferable that it allows me to modify the operations (for example I could change "==" to "equal-to").
How would I implement this? Is there a library that could do something like this, a regex statement or is it simply a matter of a long function with lots of if statements?
Formally, your situation is: you have a grammar which describes the language of expressions which you want to validate, and a word for which you want to determine whether it belongs in that language. This is a job for a parser of that language.
You could hand-cook something like a recursive-descent LL(1) parser, or use a tool to generate a parser. A well-known example of such a tool is Bison for generating LALR(1) parsers. Wikipedia has a long parser generator list.
Technical terms are used above mainly to provide entry points for googling.
You would start from defining your language more or less formally. (A language is a set of strings). A good way to define a language is to specify its context-free grammar. Describe additional conditions (like the requirement that variables must be declared, and of the right type) informally in prose.
The next step would be building a parser for your grammar specified at the previous step. There are several tools for building parsers from grammars automatically, from yacc/bison to boost::spirit.
After building and checking the parser, implement the informally-specified rules and plug them into your parser code/data.
Normally the next step, building an evaluator, would probably the easiest part of writing a simple interpreter, but you say you don't need one.
Describing your language as "just like C++ only with certain bits taken out" could be a preliminary step to the sequence outlined above. It is however not recommended to start out from C++ if you can help it. C++ is an extremely hard language to specify formally, and its parsers tend to be rather hairy, due to its convoluted declaration syntax.
you can run compiler as sub-process of your application. All you have to do is to pass arguments and parse response properly

using OCaml to simplify arithmetic expression

I am now using ocaml to deal with some arithmetic expressions. If every arithmetic expression is a string like: "1+2*(2-5)". I want to know how to use ocaml to eliminate useless parentheses.
For example if we get a string like "(2*(1-8))" we should output "2*(1-8)".
Thanks.
OCaml is just a programming language, not a symbolic algebra system. So you would solve this in OCaml just as in any general purpose language.
A full blown solution would be to parse the expression into a tree, then walk the tree to produce the output. For this you need to analyze your string lexically (for which you can probably use the Str module), and then parse the tokens. You can code your own parser pretty easily, or you could really go full force and use a parser generator like ocamlyacc.
For the relatively simple problem of reparenthesizing an arithmetic expression you can use a variant of the "shunting yard" algorithm, which in essence calculates a canonical, unparenthesized (RPN) form of an expression.

How to parse mathematical formulae from strings in c++

I want to write a program that takes an string like x^2+1 and understand it.
I want to ask the user to enter her/his function and I want to be able to process and understand it. Any Ideas?
char s[100];
s <- "x*I+2"
x=5;
I=2;
res=calc(s);
I think it could be done by something like string analyses but I think Its so hard for me.
I have another Idea and that is using tcc in main program and doing a realtime compile and run and delete a seprated program (or maybe function) that has the string s in it.
and I will create a temp file every time and ask tcc to compile it and run it by exec or similar syntax.
/*tmp.cpp:*/
#include <math.h>
void main(/*input args*/){
return x*I+2;
}
the tmp.cpp will created dynamically.
thanks in advance.
I am not sure what do you expect. It's too complex to give the code as answer, but the general idea is not very complex. It's not out of reach to code, even for a normal hobbyist programmer.
You need to define grammar, tokenize string, recognize operators, constants and variables.
Probably put expression into a tree. Make up a method for substituting the variables... and you can evaluate!
You need to have some kind of a parser. The easiest way to have math operations parsable is to have them written in RPN. You can, however, write your own parser using parser libraries, like Spirit from boost or Yacc
I use with success , function parser
from www it looks like it supports also std::complex, but I never used it
As luck would have it, I recently wrote one!
Look for {,include/}lib/MathExpression/Term. It handles complex numbers but you can easily adapt it for plain old floats.
The licence is GPL 2.
The theory in brief, when you have an expression like
X*(X+2)
Your highest level parser can parse expressions of the form A + B + C... In this case A is the whole expression.
You recurse to parse an operator of higher precedence, A * B * C... In this case A is X and B is (X+2)
Keep recursing until you're parsing either basic tokens such as X or hit an opening parenthesis, in which case push some kind of stack to track where your are and recurse into the parentheses with the top-level low-precedence parser.
I recommend you use RAII and throw exceptions when there are parse errors.
use a Recursive descent parser
Sample: it's in german, but a small and powerfull solution
look here
here is exactly what You are searching for. Change the function read_varname to detect a variable like 'x' or 'I'.

std::string to a uint64_t

How do I convert a std::string to an uint64_t? I would also like the function to throw if the string does not contain a pure representation of an uint64_t. For example, conversions of these should throw:
"NO: 9889"
"9889L"
"9889U"
"1e+22"
or indicate by another means that they are not a pure representation. I am using C++98 and boost (including boost::regex).
Use boost::lexical_cast. It will throw a bad_lexical_cast if the number can't be parsed or overflows.
If you ever switch to C++11, there's a new function in the standard for that which should be faster.
A for with isdigit() followed by a strtoll() is always an option.
Perhaps not a one-liner, but a good function to write in your stringutils.cpp.