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?

1 Like

string a[100];
gets(a);

2 Likes

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.

14 Likes

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.

1 Like

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

5 Likes

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

while(cin>>temp)

{

}

should also work

3 Likes

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

1 Like

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

can you please elxplain what is a*
I have typed this code still i do not get it

For arrays a trick is to use range based for loop: (Also works with vectors)

T arr[N];
for(T &i:arr)cin>>i;

If you use vectors, use this: (Arrays doesn’t work here)

// Add this template on top of your code
template<class A> istream& operator>>(istream& in, vector<A> &a){
    for(A &i:a)in>>i;
    return in;
}

Now you can do something like this:

vector<T> v(N);
cin>>v;

:wink:

5 Likes

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

1 Like

is it faster or something?
even if it same time of adding offset in case of indexed addressing, i dont think diff is much
coz i dont see the pt of such complicated implementation
nearly 99.99% people use what @omkarkolate suggested

3 Likes

It’s the same thing, just a shorter version.
How is this " for(T &i:arr)cin>>i; " more complicated? It’s simpler in fact…
And it doesn’t matter what other “99.99%” people use. :slight_smile:

1 Like

will it work

thank You.