Code Review Asked by ndogac on October 27, 2021
I am a newbie in stack exchange code review. I just wrote a C function where the function checks if the given string is numeric or not. What do you think about my way of doing this? And could this be done in other ways?
#include <stdio.h>
#include <stdbool.h>
bool is_numeric(const char* str)
{
while (isspace(*str))
str++;
if (*str == '-' || *str == '+')
str++;
while (*str)
{
if (!isdigit(*str) && !isspace(*str))
return false;
str++;
}
return true;
}
int main(int argc, char** argv)
{
printf("%sn", is_numeric("123436") ? "true" : "false"); // should be true
printf("%sn", is_numeric("123.436") ? "true" : "false"); // should be false
printf("%sn", is_numeric(" 567") ? "true" : "false"); // should be true
printf("%sn", is_numeric("235 ") ? "true" : "false"); // should be true
printf("%sn", is_numeric("794,347") ? "true" : "false"); // should be false
printf("%sn", is_numeric("hello") ? "true" : "false"); // should be false
printf("%sn", is_numeric("-3423") ? "true" : "false"); // should be true
}
Thanks in advance!
Bug: is_numeric("")
returns true.
Bug: is...(negative_values)
is UB. (Aside from is...(EOF)
). Possible when *str < 0
.
Bugs: as reported by user3629249
Consider allowing hex such as "0xAbC"
.
Standard library string functions operate as if char
is unsigned, even if char
is signed. Recommend to do the same here.
What do you think about my way of doing this?
I like the idea of allowing of trailing white-space when leading white-space allowed.
#include <stdbool.h>
#include <ctype.h> // missing in OP code.
bool is_numeric_integer(const char *str) {
const unsigned char *ustr = (const unsigned char *) str;
while (isspace(*ustr)) {
ustr++;
}
if (*ustr == '-' || *ustr == '+') {
ustr++;
}
const unsigned char *begin = ustr;
while (isdigit(*ustr)) {
ustr++;
}
if (begin == ustr) {
return false; // no digits.
}
// If you want to allow trailing white-space
while (isspace(*ustr)) {
ustr++;
}
return *ustr == ' '; // fail with trailing junk
}
Answered by chux - Reinstate Monica on October 27, 2021
regarding:
if (!isdigit(*str) && !isspace(*str))
the isdigit()
handles 0...9, so catches if any of the passed in char array is not numeric.
The && !isspace(*str))
has nothing to do with numeric values
Answered by user3629249 on October 27, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP