Skip to content

Instantly share code, notes, and snippets.

@Ryoga-exe
Created February 25, 2024 19:50
Show Gist options
  • Save Ryoga-exe/056bb57af2bfb6c3760913a19e87f6eb to your computer and use it in GitHub Desktop.
Save Ryoga-exe/056bb57af2bfb6c3760913a19e87f6eb to your computer and use it in GitHub Desktop.
Simple text scanner like Java for Zig. For competitive programming.
const std = @import("std");
pub const Scanner = struct {
const Self = @This();
const stdin = std.io.getStdIn();
var buffered_reader = std.io.bufferedReader(stdin.reader());
var reader = buffered_reader.reader();
buffer: [65536]u8 = undefined,
pub fn init() Self {
return Self{};
}
pub fn next(self: *Self) []const u8 {
var fbs = std.io.fixedBufferStream(&self.buffer);
const writer = fbs.writer();
for (0..fbs.buffer.len) |_| {
const byte: u8 = reader.readByte() catch unreachable;
if (std.ascii.isWhitespace(byte)) {
break;
}
writer.writeByte(byte) catch unreachable;
}
const output = fbs.getWritten();
self.buffer[output.len] = ' '; // emulating old behaviour
return output;
}
pub fn nextOwn(self: *Self, allocator: std.mem.Allocator) []const u8 {
return allocator.dupe(u8, self.next()) catch unreachable;
}
pub fn nextLine(self: *Self) []const u8 {
const line = reader.readUntilDelimiterOrEof(&self.buffer, '\n') catch unreachable;
if (@import("builtin").os.tag == .windows) {
return std.mem.trimRight(u8, line.?, "\r");
} else {
return line.?;
}
}
pub fn nextLineOwn(self: *Self, allocator: std.mem.Allocator) []const u8 {
return allocator.dupe(u8, self.nextLine()) catch unreachable;
}
pub fn nextUsize(self: *Self) usize {
return std.fmt.parseInt(usize, self.next(), 10) catch unreachable;
}
pub fn nextInt(self: *Self, comptime T: type) T {
return std.fmt.parseInt(T, self.next(), 10) catch unreachable;
}
pub fn nextFloat(self: *Self, comptime T: type) T {
return std.fmt.parseFloat(T, self.next()) catch unreachable;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment