3

Is there a way to input n of inputs into an array, where n is not fixed, using scanf()?

scanf("%d %d %d %d ... n number of inputs", &array);

The problem is that a user enters the size of an array, and the input format is that the inputs are stored using scanf in a single line, so it is of the form

12 24 36 34 65 24 54 ... upto n inputs

So that the first %d is stored in array[0], the second into array[1], third into array[2], and all the way upto array[n-1].

It is easy to make a for loop for this, but I want to do it in a single line.

4
  • 5
    Why do you want to do it in a single line when you already know of an easy way to do it? Commented Oct 29, 2018 at 16:54
  • 2
    "I want to do it in a single line." Apart from writing your own function to do it, you can't do it in a single line. But then again it wouldn't be a single line if you write a function. Commented Oct 29, 2018 at 16:55
  • 1
    Read this stackoverflow.com/questions/11695237/… and go for vfscanf() ... :-) Commented Oct 29, 2018 at 17:18
  • What is the range of n? Commented Oct 29, 2018 at 20:40

1 Answer 1

1

Not one-liner but still short

while(i < n && scanf("%d", &array[i]) == 1)
    i++;

You should always check the return value of scanf function.
Don't forget to initialize i with 0

Sign up to request clarification or add additional context in comments.

1 Comment

Don't break the line before i++ - and a one-liner it is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.