How to take input of an array in 1 line in C++?

How to take input of an array in one line?
first line will be the size of the array.
cin>>sizeofarray.

then I want to take input of a[0]- a[n-1] on the same line like this:
a[0] a[1] a[2]---- so on.
How is it possible?

string a[100];
gets(a);

1 Like

If you are referring to the sample input like this:

7
12 34 56 78 76 54 32

then, you can use

cin >> sizeofarray;
for (int i = 0; i < sizeofarray; ++i)
{
    cin >> a[i];
}

That is, you need not do anything special. Just read the array elements one-by-one like you would do otherwise.

3 Likes

IN that case it is not possible to input. You should either know the number of elements or input will be terminated by some special character. However it is possible in python if all elements are on the same line in the input file

It can be done the string way i.e. declare the string of maximum size and take input of the string, find its length and you can then know the number of elements in the input.
Ex: taking 1000 as the maximum size of input,

char arr[1000];
gets(arr);
int len=strlen(arr);

len gives the number of elements in the input array.

So many C/C++ programmers here and me - Java programmer, have to tell you, how to do it? :smiley:

The “trick” is, that scanf() return value is int

Number of receiving arguments successfully assigned

So basically you are reading like

while( scanf( "%d", &tmp) == 1 )

see the ideone code in C

3 Likes

In case if you don’t know the no. of elements to input

while(cin>>temp)

{

}

should also work

I assume that you are talking with reference to taking such input in codechef where the input are read from a file
1- C style

while ( scanf("%d",&x) != EOF )
{}

2- C++ style

while ( cin>>x )
{}

cin.clear() // For taking further inputs from cin

Alternatively,

cin>>x;

while(cin.good() == 1 )

{ cin>>x;
}

cin.clear() // For taking further inputs from cin