Basic module

string_to_int

procedure · 1 overloadSource

Reads a whole number of type T (int by default) in the given base (2 to 36) from the start of t.

string_to_int :: (
    t: string,
    base := 10,
    $T := int
) -> (result: T, success: bool, remainder: string)

Leading white space is skipped, then an optional + or -, then the digits; letters are digits above 9 and may be in either case. The result is the value, whether a number was read and the text after it. Reading stops at the first byte that is not a digit; it is not an error, so check the remainder if the whole text must be a number.

When no digits are found, the value does not fit T or a minus sign is given for an unsigned type, the result is 0, false and all of t. An unsupported base or a T that is not an integer fails an assert.

Parameters

t: string
base := 10
$T := int

Returns

result: T
success: bool
remainder: string
ExampleOpen in playground ↗
value, ok, rest := string_to_int("  -42 apples");
assert(ok && value == -42 && rest == " apples");

hex, hex_ok, _ := string_to_int("ff", 16);
assert(hex_ok && hex == 255);

small, small_ok, _ := string_to_int("300", 10, u8);
assert(!small_ok);

See also