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?
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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With