This code adds some plausible checking and uses "%1d"
for the scanf()
input format for the subsequent entry of the digits.
#include <stdio.h>
int main(void)
{
int size;
printf("Enter the size of the string: ");
if (scanf("%d", &size) != 1 || size <= 0 || size > 1024)
{
fprintf(stderr, "failed to read a valid size between 1 and 1024\n");
return 1;
}
int arr[size];
printf("Enter the String: ");
for (int i = 0; i < size; i++)
{
if (scanf("%1d", &arr[i]) != 1)
{
fprintf(stderr, "failed to read entry %d\n", i+1);
return 1;
}
}
printf("The string you've entered is: ");
int length = 0;
const char *pad = "";
for (int i = 0; i < size; i++)
{
length += printf("%s%d", pad, arr[i]);
pad = " ";
if (length > 60)
{
length = 0;
putchar('\n');
pad = "";
}
}
if (length > 0)
putchar('\n');
return 0;
}
The code was the source file scan61.c
and compiled to scan61
. Sample outputs:
$ scan61
Enter the size of the string: 13
Enter the String: 12342234323442341
The string you've entered is: 1 2 3 4 2 2 3 4 3 2 3 4 4
$ scan61
Enter the size of the string: 17
Enter the String: 1234 2234 32 34 4 2 3 4
1
The string you've entered is: 1 2 3 4 2 2 3 4 3 2 3 4 4 2 3 4 1
$ scan61
Enter the size of the string: 4
Enter the String: -1 -2 -3 -4
failed to read entry 1
$
The first sample shows that extra digits can be entered. The second shows that although the scanf()
reads single digits, they can be separated by spaces or newlines — the scanf()
family of functions is not appropriate for use when you need line-based inputs. The third shows that you cannot apply a sign to the entered numbers.