Check the whole integer input

A stock-adjustment tool accepts signed decimal counts of items. Its validation requires at least one converted digit and no trailing characters. Assume stdlib.h and stdio.h are included, all converted values fit in long, and no range errors occur.


C
const char *tokens[] = {"12", "7kg", "bad", "0", "-5"};
int accepted = 0;
long total = 0;

for (int i = 0; i != 5; ++i) {
    char *end;
    long value = strtol(tokens[i], &end, 10);
    if (end != tokens[i] && *end == '\0') {
        ++accepted;
        total += value;
    }
}
printf("%d %ld\n", accepted, total);


Find the original number of accepted inputs and the original total adjustment in items. Then run the fragment again from its initial state, replacing only the if condition with value != 0. Find the modified number of accepted inputs and modified total adjustment in items. Enter all four answers as exact integers.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More STDIO.H and STDLIB.H Questions: