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.This works because ín C,
'0'is anint-typed (yesint, notcharas you might expect) expression that evaluates to the value used to represent0in 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.