user6005857 user6005857 - 3 months ago 9
C Question

How to read space-separated 0-9 digits in C?

I am trying to make a program that reads space-separated positive digits in C and gives an error message to ANY other format of input.

For example, the following inputs are correct:

0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0
7 6 5 4 3
1 2 3
...


For all the other inputs, the program should terminate and an error message should be printed. For example:

0 1,2 3 4-5 67 89
0123456789
0a2b3c4d5e6f7g8h9i
...


Here is my attempt:

...
int inputArr[999];
int length = 0;
char c = getchar();

while ( c != '\n' ) {
if ( isdigit(c) ) {
inputArr[length] = c - '0';
length++;
} else {
printf ("Wrong Input Format!\n");
}
c = getchar();
if ( c != ' ' ) {
printf ("Wrong Input Format!\n");
} else {
continue;
}
}
...


but this gives an error message even when the input is correct.

Update:

When I input the following:

0 1 2 3 4 5 6 7 8 9


I expect the program not to give me any error messages but I get exactly 10 error messages (After removing the line
exit(1);
). I am assuming it is one error message for every character after 1 and (that is 9 messages) and 1 message for the '\n' character at the end.

Answer

Try this:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

void e() { puts("Bad input."); exit(EXIT_FAILURE); }

int main(void)
{
    for (int c1 = 0, c2 = 0; c1 != EOF && c2 != EOF; )
    {
        c1 = getchar();
        if (c1 == EOF || c1 == '\n') continue;   // file or line ends in "x "
        if (!isdigit(c1)) e();

        c2 = getchar();
        if (c2 != EOF && c2 != '\n' && c2 != ' ') e();

        printf("Got input: '%c'.\n", c1);
    }
}

This version permits trailing spaces at the end of a line. If you don't want to allow trailing spaces (i.e. "1 2" is OK but "1 2 " is an error), change the first condition to:

if (c1 == EOF || c1 == '\n' || !isdigit(c1)) e();