From 2000161d34ded07201c2c3f54d2a7b30f0d3d593 Mon Sep 17 00:00:00 2001 From: "K. Lange" Date: Wed, 29 Jun 2022 14:55:46 +0900 Subject: [PATCH] Trim trailing whitespace in string-to-int/long conversions --- src/obj_long.c | 10 +++++++++- test/day1.krk | 2 +- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/obj_long.c b/src/obj_long.c index 25f4055..f487f15 100644 --- a/src/obj_long.c +++ b/src/obj_long.c @@ -1043,6 +1043,11 @@ static int convert_digit(char c) { return 0; } +static int is_whitespace(char c) { + /* Same set we use in str.strip() by default */ + return (c == ' ' || c == '\t' || c == '\n' || c == '\r'); +} + /** * @brief Parse a number into a long. * @@ -1057,7 +1062,10 @@ static int krk_long_parse_string(const char * str, KrkLong * num, unsigned int b int sign = 1; /* Skip any leading whitespace */ - while (c < end && *c && (*c == ' ' || *c == '\t')) c++; + while (c < end && is_whitespace(*c)) c++; + + /* Trim any trailing whitespace */ + while (end > c && is_whitespace(end[-1])) end--; /* If there's nothing here, that's invalid. */ if (c >= end) { diff --git a/test/day1.krk b/test/day1.krk index 5b8998e..5528f32 100644 --- a/test/day1.krk +++ b/test/day1.krk @@ -1,6 +1,6 @@ from fileio import open let f = open('test/day1.in','r') -let lines = [int(x) for x in f.read().split("\n")][:-1] # because that split included a blank +let lines = [int(x) for x in f.readlines()] f.close() # Make a bad set