I am new to programming and to C in general and am currently studying it at university. This is for an assignment so I would like to avoid direct answers but are more after
You're checking the outcome of strtol
in the wrong order, check ptr
first, also don't check ptr against NULL
, derference it and check that it points to the NUL
('\0'
) string terminator.
if (*ptr == '\0') {
// this means all characters were parsed and converted to `long`
}
else {
// this means either no characters were parsed correctly in which
// case the return value is completely invalid
// or
// there was a partial parsing of a number to `long` which is returned
// and ptr points to the remaining string
}
num > 1000001
also needs to be num > 1000000
num < 0
also needs to be num < 1
You can also with some reorganising and logic tweaks collapse your sequence of if statements down to only a single invalid branch and a okay branch.