1

How can we take multiple number of integer inputs by user choice in c in runtime. Here the first line of the input is the number of test cases. Then I am calculating the sum of the input numbers in this case.

The test case :

Input

3
1 6 7
2 7 3 4
2 1

Output:

14
16
3

Can we modify scanf() in this way so it can process this dynamic inputs.

I can't take the line as a string input and then split them into numbers.

Can we use the space and \n both to decide the numbers as we do to take strings as input as an example: scanf("%[^\n]",&str);

13
  • scanf("%d",&num) will do the trick. But do you know how many numbers will be inputted in each test case? or is it random? Commented May 8, 2015 at 13:47
  • 1
    "I can't take the line as a string input and then split them into numbers." — why is the obvious solution not allowed? Commented May 8, 2015 at 13:52
  • I was trying to use variable arguments in c, but failed, I use that technique not string @squeamishossifrage Commented May 8, 2015 at 13:53
  • It is random @CoolGuy Commented May 8, 2015 at 13:58
  • 3
    ideone.com/2Hhqe2 Commented May 8, 2015 at 14:19

1 Answer 1

1

The answer was provided by BLUEPIXY by his nice code. Here we will consider inputs as a pair.

Either it will be a pair of number and space or it will be a pair of number and newline character.

Example: 2 3 4

So in this input we take as pairs, like - '2', '3' and '4\n'. When we encounter a \n we stop the infinite loop. Here the code goes:

#include <stdio.h>

int main(void){
    int n;

    scanf("%d", &n);
    while(n--){
        int v, sum = 0;
        while(1){
            char ch = 0;
            scanf("%d%c", &v, &ch);
            sum += v;
            if(ch == '\n' || ch == 0)
                break;
        }
        printf("%d\n", sum);
    }

    return 0;
}

Inputs:

3
1 6 7
2 7 3 4
2 1

Output:

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

2 Comments

Minor holes with this approach is that it relies on 1) the '\n' following number and 2) line has at least 1 number 3) input text is always numeric.
@chux Yeah you are right that the input text is always need to be numeric.

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.