Nyx by Example

Stdin Input

Reading from standard input in Nyx is done with read_line(), which blocks until the user presses Enter and returns the typed text as a String. A companion function print_no_newline lets you display a prompt without advancing to the next line, keeping the cursor right after the colon.

Code

// Leer una línea de stdin con read_line() y saludar al usuario
// En CI/testing: redirigir stdin con echo "Alice" | ./programa

fn main() -> int {
    print_no_newline("Ingresa tu nombre: ")

    // read_line() lee hasta '\n' desde stdin
    let nombre: String = read_line()

    // Eliminar posible '\n' al final con trim
    let nombre_limpio: String = nombre.trim()

    if nombre_limpio.length() == 0 {
        print("Hola, desconocido!")
    } else {
        print("Hola, " + nombre_limpio + "! Bienvenido a Nyx.")
    }

    print("Longitud del nombre: " + int_to_string(nombre_limpio.length()))

    return 0
}

Output

Ingresa tu nombre: Alice
Hola, Alice! Bienvenido a Nyx.
Longitud del nombre: 5

Explanation

print_no_newline(s) writes a string to stdout without appending a newline, unlike the regular print. This is the idiomatic way to display an inline prompt so the user's input appears on the same line.

read_line() reads characters from stdin until it encounters a newline character. The returned string may include a trailing \n depending on the platform and how input was piped, so calling .trim() is good practice to strip leading and trailing whitespace.

The if/else guard handles the empty-input case gracefully. In automated testing you can feed input via shell redirection: echo "Alice" | ./programa, which makes read_line() return "Alice\n" without blocking.

← Previous Next →

Source: examples/by-example/12-stdin-input.nx