[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
5.15.2 Expression input
GiNaC provides no way to directly read an expression from a stream because
you will usually want the user to be able to enter something like ‘2*x+sin(y)’
and have the ‘x’ and ‘y’ correspond to the symbols x
and
y
you defined in your program and there is no way to specify the
desired symbols to the >>
stream input operator.
Instead, GiNaC lets you construct an expression from a string, specifying the list of symbols to be used:
{ symbol x("x"), y("y"); ex e("2*x+sin(y)", lst(x, y)); } |
The input syntax is the same as that used by ginsh
and the stream
output operator <<
. The symbols in the string are matched by name to
the symbols in the list and if GiNaC encounters a symbol not specified in
the list it will throw an exception.
With this constructor, it's also easy to implement interactive GiNaC programs:
#include <iostream> #include <string> #include <stdexcept> #include <ginac/ginac.h> using namespace std; using namespace GiNaC; int main() { symbol x("x"); string s; cout << "Enter an expression containing 'x': "; getline(cin, s); try { ex e(s, lst(x)); cout << "The derivative of " << e << " with respect to x is "; cout << e.diff(x) << ".\n"; } catch (exception &p) { cerr << p.what() << endl; } } |