Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get multiple inputs in one line in C?

Tags:

c

input

scanf

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?

like image 847
Soham Avatar asked May 07 '14 19:05

Soham


People also ask

How do you take multiple inputs in one line?

# Taking multiple inputs in a single line. # and type casting using list() function. x = list(map(int, input("Enter multiple values: "). split()))

Can scanf take multiple inputs?

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.

How do I scanf in the same line?

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.


1 Answers

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);
}
like image 138
ccKep Avatar answered Sep 29 '22 19:09

ccKep