The problem with using the function scanf
is that it will ignore whitespace characters. Since the newline character is a whitespace character, this means that scanf
will ignore any newline characters. Therefore, if you want to enforce that all numbers entered are in the same line, then you should not be using the function scanf
.
In order to read a single line of input, I recommend that you use the function fgets
. After reading one line of input, you can use the function strtol
to attempt to convert the characters to numbers.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define N 10
int main( void )
{
int arr[N];
char line[500], *p;
//prompt user for input
printf( "Please enter %d numbers: ", N );
//attempt to read one line of input
if ( fgets( line, sizeof line, stdin ) == NULL )
{
fprintf( stderr, "Input error!\n" );
exit( EXIT_FAILURE );
}
//attempt to read 10 numbers
p = line;
for ( int i = 0; i < N; i++ )
{
char *q;
arr[i] = strtol( p, &q, 10 );
if ( q == p )
{
printf( "Error converting #%d!\n", i + 1 );
exit( EXIT_FAILURE );
}
p = q;
}
//verify that the remainder of the line contains nothing
//except whitespace characters
for ( ; *p != '\0'; p++ )
{
if ( !isspace( (unsigned char)*p ) )
{
printf( "Error: Non-whitespace character found after 10th number!\n" );
exit( EXIT_FAILURE );
}
}
//print results
for ( int i = 0; i < N; i++ )
{
printf( "%d ", arr[i] );
}
return 0;
}
This program has the following behavior:
Please enter 10 numbers: 1 2 3 4 5
Error converting #6!
Please enter 10 numbers: 1 2 3 4 5 6 7 8 9 10 11
Error: Non-whitespace character found after 10th number!
Please enter 10 numbers: 1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Note that my code above has the following issues:
It will not check whether the line was too long to fit into the input buffer (i.e. longer than 500 characters).
It will not check whether the number the user entered is representable as an int
(i.e. whether it is larger than INT_MAX
, which is 2,147,483,647 on most platforms).
If you also want to address these issues, that I suggest that you take a look at my function get_int_from_user
in this answer of mine to another question.