Space separated multiple inputs on single line(C++)

5 1256 4323 7687 3244 5678
2 2334 7687
5 2334 5678 6547 9766 9543

I am supposed to input in the above form. The first integer in each line decides the number of integers that follow. Since the first integer can vary, I do not know if it is possible with ‘scanf’.

Hello @lytkillr262,

I think that this code snippet solves your problem:

#include <stdio.h>

int main()
{
	int x;
	scanf("%d", &x);
	for(int i = 0; i < x;i++)
	{
		int elem;
		scanf("%d", &elem);
	}
	return 0;
}

What you need to take care of, is actually the 1st integer you read, that will control the for loop that will allow you to input all the other numbers…

Hope I could help,

Bruno

this can be easily done by scanf using the above method mentioned by @kuruma because

5 1256 4323 7687 3244 5678
2 2334 7687
5 2334 5678 6547 9766 9543

is same as:

5 
1256 
4323 
7687 
3244 
5678
2 
2334 
7687
5 
2334 
5678 
6547 
9766 
9543

I think you got the answer of your problem.
Happy Coding.

2 Likes

Understood the code.That worked. I should give more time to understand scanf and cin completely.
Thanks. M commenting after successful submission on first attempt. :slight_smile:

Yes, that worked. Thanks :slight_smile: