Advertisement
Guest User

fn retry when overflow input buffer

a guest
Jan 28th, 2022
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. const std = @import("std");
  2.  
  3. fn flush(reader: anytype) @TypeOf(reader).Error!void {
  4. var scratch: [64]u8 = undefined;
  5. while (try reader.read(&scratch) != 0) {}
  6. }
  7.  
  8. fn nextLine(reader: anytype, buffer: []u8) !?[]const u8 {
  9. var line = (try reader.readUntilDelimiterOrEof(
  10. buffer,
  11. '\n',
  12. )) orelse return null;
  13. // trim annoying windows-only carriage return character
  14. if (@import("builtin").os.tag == .windows) {
  15. return std.mem.trimRight(u8, line, "\r");
  16. } else {
  17. return line;
  18. }
  19. }
  20.  
  21. pub fn main() anyerror!void {
  22. const stdout = std.io.getStdOut();
  23. const stdin = std.io.getStdIn();
  24.  
  25. try stdout.writeAll(
  26. \\ Enter ten bytes or less:
  27. );
  28.  
  29. var buffer: [10]u8 = undefined;
  30.  
  31. const input = while (true) {
  32. const x = nextLine(stdin.reader(), &buffer) catch {
  33. flush(stdin.reader());
  34. continue;
  35. };
  36. break x;
  37. } else unreachable; // (see comment) fallback value could be an empty string maybe?
  38.  
  39. try stdout.writer().print("You entered: \"{s}\"\n", .{input});
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement