1
#include <iostream>


template <typename T>
void Len(T a[200])
{
    std::cout<< sizeof(a) / sizeof(a[0])<<std::endl;
}

int main()
{
    int a[300];
    std::cout<<"Put the values of array you want."<<std::endl;
    std::cin>>a;
    std::cout<<"The number of occurrences of value in the array is";
    Len(a);

}

why this code get error in std::cin>>a? I make code in C++ nearly first time. Please answer:(

j.doe
  • 11
  • 1
  • 2
    You can't input to an array like that, you have to read each and every entry one by one (for example in a loop). – Some programmer dude Sep 29 '15 at 12:25
  • 1
    Also, as arrays decays to pointers if you pass them to a function, when you do `sizeof(a)` in the `Len` function you will not get the size of the array, but the size of the pointer (which will be `8` or `4` depending on if you're on a 64 or 32 bit platform). – Some programmer dude Sep 29 '15 at 12:26
  • 3
    Instead of trying out code at random you should learn from a good [book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – user657267 Sep 29 '15 at 12:27

1 Answers1

4

you cannot input directly into an array like std::cin >> a;. What you need to do is loop through the array and insert the input into each element. You can do that with

for(int i = 0; i < array_size && std::cin >> array_name[i]; ++i) {}

Also you array size function is incorrect.

template <typename T>
void Len(T a[200])
{
    std::cout<< sizeof(a) / sizeof(a[0])<<std::endl;
}

Here a will decay to a pointer and the size returned will be sizeof(T*)/sizeof(T)

If you want to get the size of the array you can use

template <typename T, typename size_t N>
size_t get_array_size(T (&)[N])
{
    return N;
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • I would add a check for end-of-file or failure in that loop condition. I know that *I* would tire entering numbers after just a few numbers, entering 300 is way to many and I would just press the platforms EOF key-combination. :) – Some programmer dude Sep 29 '15 at 12:28
  • @JoachimPileborg I added the input into the conditional part. That should handle those cases. – NathanOliver Sep 29 '15 at 12:29