I want to make a program that allows the use to input space separated numbers then read those numbers into an array. I wrote a program which works for all cases except when the user inputs data that is separated by more than 1 space or has multiple trailing spaces.
Sample input and output:
Code:
Input:"0 1 2 3 4 5 6 7 8 9"
Output: [0,1,2,3,4,5,6,7,8,9]
Input:"0 1 2 3 4 5 6 7 8 9 "
Output: [0,1,2,3,4,5,6,7,8,9]
Input:"0123456789"
Output: Error: Bad input format.
Input:"0 1 24 3 5 12 4 6"
Output: Error: Bad input format.
Input:"0 1 2.3 4 5 6,7"
Output: Error: Bad input format.
Input:"0 1 2 -3 4 -5 6 7"
Output: Error: Bad input format.
Input:"0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9"
Output: Error: Too many numbers.
Code:
int input_array[10] = { 0 };
int size = 0;
int ch1 = 0, ch2 = 0;
while (ch1 != '\n' && ch2 != '\n') {
ch1 = getchar();
if (ch1 == EOF || ch1 == '\n' || !isdigit(ch1)) {
printf("Error: Bad input format.");
exit(EXIT_FAILURE);
}
ch2 = getchar();
if (ch2 != EOF && ch2 != '\n' && ch2 != ' ') {
printf("Error: Bad input format.");
exit(EXIT_FAILURE);
} else {
input_array[size] = ch1 - '0';
size+=1;
}
if ((ch1 == '\n' || ch2 == '\n') && size != DICE_SIZE) {
printf("Error: Too many numbers.");
exit(EXIT_FAILURE);
}
}
The code above works for all cases except when the inputs are not separated by exactly 1 space with no trailing or leading spaces, so I get an error for the following input but
Code:
Input:"0 1 2 3 4 5 6 7 8 9 "
Output: Error: Bad input format.
Desired Output: [0,1,2,3,4,5,6,7,8,9]
I modified the code above and now it works for this input "0 1 2 3 4 5 6 7 8 9 " but it stopped working for "0123456789", i.e. I get:
Code:
Input:"0123456789"
Output: [0,1,2,3,4,5,6,7,8,9]
Desired Output: Error: Bad input format.