Onyx Examples

Back to example list

Standard Input

Brendan Hansen

This example reads a single line of input from standard input, splits it in half on the first space using string.bisect, converts both parts to integers using conv.parse, then prints the results using printf for formatted printing.
// Use the necessary core libraries
use core.io { Reader }
use core.conv

// Use the printf function that lives in the core package.
// This cannot be `use core.printf`, because that will look
// for a package called `printf` in `core`.
use core {
    printf, stdio
}

main :: () {
    // Create a io.Reader over the stdio.stream to be able scan
    // the input in parts. Also, defer freeing the reader until
    // the end of `main`.
    stdin_reader := Reader.make(&stdio.stream);
    defer Reader.free(&stdin_reader);

    // Read a single line of input.
    line := stdin_reader->read_line();

    // Split the line on the first space.
    a_str, b_str := line->bisect(" ");

    // Parse and convert both parts to i32s, with a default value
    // of 0 if it fails to parse as an i32.
    a_value := conv.parse(i32, a_str)->value_or(0);
    b_value := conv.parse(i32, b_str)->value_or(0);

    // Compute our result.
    result := a_value + b_value;

    // Output our result using formatted printing.
    printf("{} + {} = {}\n", a_value, b_value, result);
}

Want to learn more?

Visit the docs!

You can learn more details about Onyx by visiting the docs! There is more examples, a reference manual for the language, and documentation for the standard library.

© 2020-2024 Brendan Hansen