Eew, what awful code.
>while (isspace (*string)) string++;
This might work if <ctype.h> were included.
>char *p;
This certainly won't work until p is given something valid to point to. Try changing it to
>scanf("%[0-9 ]",&p);
Wow, non-portable, unsafe and undefined behavior all at the same time. Impressive. fgets would be better, but I can see why scanf was used. It would make more sense if the return value were checked. Since restricting valid input was the intention to begin with, it's silly to ignore a failure code.
I personally would have used fgets and sscanf myself:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void complain ( void )
{
fprintf ( stderr, "Invalid input\n" );
exit ( EXIT_FAILURE );
}
long sumofall ( const char *buffer )
{
long part;
long sum = 0;
int n; /* The number of characters converted by sscanf */
while ( sscanf ( buffer, "%ld%n", &part, &n ) == 1 ) {
sum += part;
buffer += n;
}
if ( *buffer != '\0' )
complain();
return sum;
}
int main ( void )
{
char buffer[BUFSIZ];
printf ( "Enter a list of numbers: " );
fflush ( stdout );
if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
char *newline = strchr ( buffer, '\n' );
if ( newline != NULL )
*newline = '\0';
printf ( "%ld\n", sumofall ( buffer ) );
}
return EXIT_SUCCESS;
}