Andrew Kelley b0d2ebe529 remove std.io.readLine
This was deceptive. It was always meant to be sort of a "GNU readline"
sort of thing where it provides a Command Line Interface to input text.
However that functionality did not exist and it was basically a red
herring for people trying to read line-delimited input from a stream.

In this commit the API is deleted, so that people can find the proper
API more easily.

A CLI text input abstraction would be useful but may not even need to be
in the standard library. As you can see in this commit, the guess_number
CLI game gets by just fine by using `std.fs.File.read`.
2020-02-20 15:30:00 -05:00

47 lines
1.4 KiB
Zig

const builtin = @import("builtin");
const std = @import("std");
const io = std.io;
const fmt = std.fmt;
pub fn main() !void {
const stdout = &io.getStdOut().outStream().stream;
const stdin = io.getStdIn();
try stdout.print("Welcome to the Guess Number Game in Zig.\n", .{});
var seed_bytes: [@sizeOf(u64)]u8 = undefined;
std.crypto.randomBytes(seed_bytes[0..]) catch |err| {
std.debug.warn("unable to seed random number generator: {}", .{err});
return err;
};
const seed = std.mem.readIntNative(u64, &seed_bytes);
var prng = std.rand.DefaultPrng.init(seed);
const answer = prng.random.range(u8, 0, 100) + 1;
while (true) {
try stdout.print("\nGuess a number between 1 and 100: ", .{});
var line_buf: [20]u8 = undefined;
const amt = try stdin.read(&line_buf);
if (amt == line_buf.len) {
try stdout.print("Input too long.\n", .{});
continue;
}
const line = std.mem.trimRight(u8, line_buf[0..amt], "\r\n");
const guess = fmt.parseUnsigned(u8, line, 10) catch {
try stdout.print("Invalid number.\n", .{});
continue;
};
if (guess > answer) {
try stdout.print("Guess lower.\n", .{});
} else if (guess < answer) {
try stdout.print("Guess higher.\n", .{});
} else {
try stdout.print("You win!\n", .{});
return;
}
}
}