PR3-Klausur-Uben/ZIG/Zahlenraten.zig

45 lines
1.4 KiB
Zig

const std = @import("std");
pub fn main() !void {
const rand = std.crypto.random;
const reader = std.io.getStdIn().reader();
const writer = std.io.getStdOut().writer();
try writer.print("Welcome to my number guessing game! \n", .{});
try writer.print("Enter an upper limit\n", .{});
const upperLimit = oneIntInput(writer, reader);
try writer.print("Your upper limit is {d}! \n", .{upperLimit});
for (0..10) |i| {
const randomInt = rand.intRangeLessThan(u16, 0, 3);
try writer.print("Random number {d}: {d} \n\n", .{i, randomInt});
}
}
pub fn oneIntInput(writer: anytype, reader: anytype) !i64 {
var buffer: [256]u8 = undefined;
while (true) {
try writer.print("> ", .{});
const amountInputBytes = try reader.read(&buffer);
const input_slice: []u8 = buffer[0..(amountInputBytes - 1)];
const result: i64 = std.fmt.parseInt(i64, input_slice, 10) catch |err| {
switch (err) {
error.InvalidCharacter => {
try writer.print("Error: Invalid character, try again! \n", .{});
},
error.Overflow => {
try writer.print("Error: Too big for an i64, try again! \n", .{});
},
}
try writer.print("\n", .{});
continue;
};
return result;
}
}