Number Parsing in Modelica

Our example demonstrates how to parse numbers from strings in Modelica. This is a common task in many programs.

model NumberParsing
  import Modelica.Utilities.Strings;
  import Modelica.Utilities.Types.StringReal;
  import Modelica.Utilities.Types.StringInteger;

equation
  // Parse a float
  StringReal f = Strings.scanReal("1.234");
  Modelica.Utilities.Streams.print(String(f));

  // Parse an integer
  StringInteger i = Strings.scanInteger("123");
  Modelica.Utilities.Streams.print(String(i));

  // Parse a hexadecimal number
  StringInteger d = Strings.scanInteger("0x1c8", 16);
  Modelica.Utilities.Streams.print(String(d));

  // Parse an unsigned integer
  StringInteger u = Strings.scanInteger("789");
  Modelica.Utilities.Streams.print(String(u));

  // Parse a basic base-10 integer
  StringInteger k = Strings.scanInteger("135");
  Modelica.Utilities.Streams.print(String(k));

  // Handling parsing errors
  StringInteger e;
  when Strings.scanInteger("wat") then
    Modelica.Utilities.Streams.print("Error: Invalid syntax");
  end when;

end NumberParsing;

In Modelica, we use the Modelica.Utilities.Strings library for parsing strings into numbers. Here’s a breakdown of the operations:

  1. We use Strings.scanReal() to parse floating-point numbers.
  2. Strings.scanInteger() is used to parse integers. By default, it assumes base 10.
  3. For hexadecimal numbers, we can specify the base (16) as the second argument to Strings.scanInteger().
  4. Modelica doesn’t have a separate unsigned integer type, so we use scanInteger() for both signed and unsigned integers.
  5. There’s no direct equivalent to Atoi(), but scanInteger() serves the same purpose for basic base-10 integer parsing.
  6. Error handling in Modelica is typically done using the when clause. If an invalid string is provided, it will trigger an event and print an error message.

Note that Modelica is primarily used for modeling and simulation, so its string parsing capabilities might be more limited compared to general-purpose programming languages. The exact behavior and available functions may vary depending on the Modelica implementation you’re using.

To run this model, you would typically use a Modelica simulation environment. The output would depend on how the simulation is set up, but it should print the parsed numbers in order.

Next, we’ll look at another common parsing task: URLs.