Your loop limit is wrong. It is causing you to evaluate indeterminate data. Things specifically wrong:
- Not checking for success of
scanf
- Not specifying a length-limited format string to avoid overflowing the
c[]
array.
- As mentioned, iterating the entire array rather than just the data you assume was read successfully.
All of these can be fixed, some of them trivially.
- Check that
scanf
returned 1
- As your
c
array is 15 characters, and space must be accounted for the terminating nullchar, use %14s
for your format string
- Either use
strlen
as the limit of your for (in some fashion, be it saved to a temporary or directly in the conditional clause) or use a pointer.
Regarding the last item, I prefer the latter, as you're only scanning the string once. strlen
will scan the string to find the terminator, thereby calculating the length and returning it. Scanning it again during iteration then ensues. You can eliminate the strlen
scan by simply not using it, rather using a pointer instead, and stopping scanning when the terminator is discovered.
Rewritten, this is the result:
#include <stdio.h>
#include <ctype.h>
int main()
{
char c[15];
int j = 0;
printf("Give surname: ");
if (scanf("%14s", c) == 1)
{
for (const char *p = c; *p; ++p)
{
if (isalpha(*p))
{
printf("%c ", *p);
++j;
}
}
printf("\nNumber of characters: %d", j);
}
return 0;
}
Input
123john456
Output
j o h n
Number of characters: 4