Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use cin for an array

Tags:

c++

When I run this code

#include <iostream>
#include <string>
#include <math.h>
using namespace std;

int main() {

    int Array[100];

    cin >> Array;

    return 0;
}

I get the following error message at the cin line:

Invalid operands to binary expression ('std::__1::istream' (aka 'basic_istream') and 'int *

Why can't I directly input an array? And how do I fix the problem?

like image 800
Elias S. Avatar asked Sep 18 '18 10:09

Elias S.


2 Answers

For more modern C++ approach:

#include <algorithm>

and do

std::for_each(std::begin(Array), std::end(Array), [](auto& elem) { cin >> elem; });

or you could use it as operator>> overload

#include <iostream>
#include <algorithm>

template<typename T, size_t Size>
std::istream& operator>>(std::istream& in, T (&arr)[Size])
{
    std::for_each(std::begin(arr), std::end(arr), [&in](auto& elem) {
        in >> elem;
    });

    return in;
}

int main() {

    int Array[100] = { 0 };

    std::cin >> Array;

    return 0;
}
like image 194
fhaus Avatar answered Sep 19 '22 09:09

fhaus


One can write an overload of >> to read into a c-style array, and then your main will work fine.

template <typename T, std::size_t N>
std::istream & operator>>(std::istream & is, T (&arr)[N])
{
    std::copy_n(std::istream_iterator<T>(is), N, arr);
    return is;
}
like image 26
Caleth Avatar answered Sep 23 '22 09:09

Caleth