I know that I can use
scanf("%d %d %d",&a,&b,&c):
But what if the user first determines how many input there'd be in the line?
# Taking multiple inputs in a single line. # and type casting using list() function. x = list(map(int, input("Enter multiple values: "). split()))
Inputting Multiple ValuesIf you have multiple format specifiers within the string argument of scanf, you can input multiple values. All you need to do is to separate each format specifier with a DELIMITER - a string that separates variables.
scanf will start reading the string at the first non-whitespace character and stop reading it at the first whitespace character. Then just take the first character from the buffer you read the string into.
You are reading the number of inputs and then repeatedly (in a loop) read each input, eg:
#include <stdio.h>
#include <stdlib.h>
int main(int ac, char **av)
{
int numInputs;
int *input;
printf("Total number of inputs: ");
scanf("%d", &numInputs);
input = malloc(numInputs * sizeof(int));
for (int i=0; i < numInputs; i++)
{
printf("Input #%d: ", i+1);
scanf("%d", &input[i]);
}
// Do Stuff, for example print them:
for (int i=0; i < numInputs; i++)
{
printf("Input #%d = %d\n", i+1, input[i]);
}
free(input);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With