I'm trying to create a simple program or function that will take the users input which could be a valid hex number.
I'm trying to work out a way to verify that it's a correct hex value and return the hex value if it's true or return an error message if it's false.
I was thinking of a function that checks every char to make sure its 0-9
or A-F
but can't think how to implement this.
Thanks.
Given const char *s
, if you want to determine if every character in the string pointed to by s
is a valid hex digit you can use:
if (s[strspn(s, "0123456789abcdefABCDEF")] == 0)
{
/* valid */
}
Something like this (since you insist it isn't homework, I will fill in):
int CheckMyString(const char *aStr)
{
const char *curr = aStr;
while (*curr != 0)
{
if (('A' <= *curr && *curr <= 'F') || ('a' <= *curr && *curr <= 'f') || '0' <= *curr && *curr <= '9'))
{
++curr;
}
else
{
return 0;
}
}
return 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With