I've spent a lot of time reading c tutorials and getting this code to compile/ work properly (as i suck at c) and I want to know what a cleaner/neater way of using a strtol would be instead of getchar(c)
then changing c
to an array chstr[]
then using strtol
on chstr
.
Thanks Lachlan p.s. thanks to those that helped me with the isdigit checking
int main()
{
char c;
while((c = getchar()) !=EOF) {
if (!check_chr(c)) {
return 0;
}
}
return 1;
}
int check_chr(char c)
{
int a; char chstr[2];
if (isdigit(c)) {
chstr[0] = c; chstr[1] = "/0";
a = (strtol(chstr,0,0));
i = i + a;
return 1;
}
if (c == ',')
return 1;
if (c == '\n')
return 1;
return 0;
}
To convert a character holding a single digit into a binary number, just subtract the encoded form of '0'
. This works since C guarantees that the character encoding has 0..9 in consecutive locations.
int digit_to_number(char c)
{
if (isdigit(c))
return c - '0';
return -1;
}
This works because ín C, '0'
is an int
-typed (yes int
, not char
as you might expect) expression that evaluates to the value used to represent 0
in the target machine's encoding. For machines running e.g. ASCII or UTF-8 encodings natively, this value is (decimal) 48. For systems running EBCDIC, the value is (decimal) 240.
Using the character literal makes the translation of a character-digit into a number the compiler's problem, which is of course how it should be.