Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

is_str_num() is not handling negative numbers #1109

Open
rtxa opened this issue Aug 7, 2024 · 2 comments
Open

is_str_num() is not handling negative numbers #1109

rtxa opened this issue Aug 7, 2024 · 2 comments

Comments

@rtxa
Copy link
Contributor

rtxa commented Aug 7, 2024

The is_str_num() function in string_stocks.inc currently does not handle negative numbers. The function only checks for the presence of digits in the string, without considering a leading negative sign which may be useful in some cases and that makes the function name misleading.

Updating is_str_num() may affect any existing code that relies on that behaviour, so maybe a new stock like is_str_num_ex() would be needed or a new optional parameter to allow negative numbers check. A note warning about this would be useful too.

Proposed fix

stock bool:is_str_num_ex(const sString[]) {
    new i = 0;
    new bool:is_negative = false;

    if (sString[0] == '-') {
        is_negative = true;
        i++;
    }

    while (sString[i] && isdigit(sString[i])) {
        i++;
    }

    return sString[i] == 0 && i != (is_negative ? 1 : 0);
}

Test code:

		server_print("Is str '' num? %d", is_str_num_ex(""));
		server_print("Is str '--' num? %d", is_str_num_ex("--"));
		server_print("Is str '-' num? %d", is_str_num_ex("-"));
		server_print("Is str '-0' num? %d", is_str_num_ex("-0"));
		server_print("Is str '0' num? %d", is_str_num_ex("0"));
		server_print("Is str '1000' num? %d", is_str_num_ex("1000"));
		server_print("Is str '-1000' num? %d", is_str_num_ex("-1000"));

Output:

Is str '' num? 0
Is str '--' num? 0
Is str '-' num? 0
Is str '-0' num? 1
Is str '0' num? 1
Is str '1000' num? 1
Is str '-1000' num? 1
@dvander
Copy link
Member

dvander commented Aug 7, 2024 via email

@rtxa
Copy link
Contributor Author

rtxa commented Aug 8, 2024

Call it parse_int, make it have a bool return and optional int outparam

Already exists str_to_num() but you can't rely on it because it returns 0 on failure, and the input string can be a 0, unless we check that the string first digit isn't a 0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants