Say if I want to ask the user to enter one input or two inputs or three. For example:
int num_1, num_2, num_3;
printf("Enter input" );
Now I'm struggling to find how to scan either one, two or three. If I do this:
scanf("%d %d %d", &num_1, &num_2, &num_3);
it won't work if the user inputs only one or two inputs. So how do I do it?
CodePudding user response:
You should use a cycle and an array for the inputs, for example:
/* array where the inputs will be stored. It has the maximum
number of elements (3), assuming you want to use static arrays */
int inputs[3];
int n_inputs, i;
/* ask the user how many values he wants to put */
printf("Number of inputs: \n");
if(scanf("%d", &n_inputs) != 1) {
fprintf(stderr, "scanf fail!\n");
exit(EXIT_FAILURE);
}
/* ask for the inputs values */
printf("inputs [%d]: \n", n_inputs);
for(i = 0; i < n_inputs; i ) {
if(scanf("%d", &inputs[i]) != 1) {
fprintf(stderr, "scanf fail!\n");
exit(EXIT_FAILURE);
}
}
*edited to add scanf basic error handling.
CodePudding user response:
You can use loop for multiple input. First take the number of input, then loop through that.
For example:
int n, i;
printf("Please enter the input threshold: ");
scanf("%d", &n);
int arr[n];
for (i = 0; i < n; i ) {
printf("Enter number #%d: ", i 1);
scanf("%d", &arr[i]);
}
CodePudding user response:
The following program will read exactly one line of input and read up to MAX_INPUTS
(defined as 3
) numbers from that line.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define MAX_INPUTS 3
#define MAX_LINESIZE 80
int main( void )
{
long inputs[MAX_INPUTS];
int num_inputs;
char line[MAX_LINESIZE], *p;
//prompt user for input
printf( "Please enter up to %d numbers: ", MAX_INPUTS );
//attempt to read one line of input
if ( fgets( line, sizeof line, stdin ) == NULL )
{
fprintf( stderr, "error reading line\n" );
exit( EXIT_FAILURE );
}
//verify that entire line was read in
if ( strchr( line, '\n' ) == NULL )
{
fprintf( stderr, "line too long\n" );
exit( EXIT_FAILURE );
}
for (
num_inputs = 0, p = line;
num_inputs < MAX_INPUTS;
num_inputs
)
{
char *q;
errno = 0;
//attempt to convert one number
inputs[num_inputs] = strtol( p, &q, 10 );
if ( p == q )
break;
//make p point to end of inputted number
p = q;
//make sure that entered number is representalbe as "long int"
if ( errno == ERANGE )
{
fprintf( stderr, "number is out of range\n" );
exit( EXIT_FAILURE );
}
}
//output the inputted data
printf( "You entered %d inputs. The values are:\n" );
for ( int i = 0; i < num_inputs; i )
{
printf( "%ld\n", inputs[i] );
}
}
This is what happens when I run this program:
Please enter up to 3 numbers: 80 30
You entered 2 inputs. The values are:
80
30
CodePudding user response:
Use a simple for loop and an array:
int arr[3];
for (int i = 0; i < 3; i )
scanf("%d", &arr[i]);