File: calc.cpp

package info (click to toggle)
muparserx 4.0.8%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,132 kB
  • sloc: cpp: 10,590; makefile: 62; ansic: 14
file content (59 lines) | stat: -rw-r--r-- 1,720 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "mpParser.h"


void Calc()
{
  char line[100];
  try
  {
    // Create value objects that will be bound to parser variables
    Value fVal = 1.11;
    Value sVal = "hello world";
    Value arr1(3, 0);
    arr1[0] = 1.11, 
    arr1[1] = 2.22;
    arr1[2] = 3.33;

    Parser  parser;
    
    // Define parser variables and bind them to their value objects
    parser.DefineVar("va", Variable(&arr1));
    parser.DefineVar("a",  Variable(&fVal));
    parser.DefineVar("sa", Variable(&sVal));

    parser.SetExpr("sin(a)+b");

    // The returned result is of type Value, value is a Variant like
    // type that can be either a boolean an integer or a floating point value
    Value result = parser.Eval();

    // Value supports C++ streaming like this:
    cout << "Result:\n" << result << "\n";

    // Or if you need the specific type use this:
    switch (result.GetType())
    {
    case 's': cout << result.GetString() << " (string)" << "\n"; break;
    case 'i': cout << result.GetInt() << " (int)" << "\n"; break;
    case 'f': cout << result.GetFloat() << " (float)" << "\n"; break;
    case 'c': cout << result.GetFloat() << "+" << result.GetImag() << "i (complex)" << "\n"; break;
    case 'b': break;
    }
  }
  catch(ParserError &e)
  {
    cout << e.GetMsg() << "\n\n";

    if (e.GetContext().Ident.length()) 
      cout << "Ident.: " << e.GetContext().Ident << "\n";

    if (e.GetExpr().length()) 
      cout << "Expr.: " << e.GetExpr() << "\n";

    if (e.GetToken().length()) 
      cout << "Token: " << e.GetToken() << "\n";

    cout << "Pos:   " << e.GetPos() << "\n";
    cout << "Errc:  " << e.GetCode() << "\n";
  }
} // Calc()