3

What is the easiest way to read space separated input into an array?

//input:5
        1 2 3 4 7



int main() {
    int n;
    cin>>n;
    int array[n];
    for (int i =0;i<n;i++){
        cin>>array[i];
    }
    cout<<array; 
    return 0;
}  

I tried the code above but the output is 0x7ffe42b757b0.

J.Ren
  • 65
  • 1
  • 1
  • 6

3 Answers3

5

The problem lies with your printing. Since array is a pointer, you are only printing an address value.

Instead, do this:

for (int i =0;i<n;i++){
    cout<< array[i] << " ";
}
Lincoln Cheng
  • 2,263
  • 1
  • 11
  • 17
  • Thank you very much.That's the problem.I have had many problems like this since I changed to C++ from Python. – J.Ren Apr 07 '16 at 09:11
  • @J.Ren. C++ has many features to offer that prevent you from having to use fixed size arrays. In my example you can put an input string of any size. – Chiel Apr 07 '16 at 09:16
3

You can do that by passing std::istream_iterator to std::vector constructor:

std::vector<int> v{
    std::istream_iterator<int>{std::cin}, 
    std::istream_iterator<int>{}
    };

std::vector has a constructor that accepts 2 iterators to the input range.

istream_iterator<int> is an iterator that reads int from a std::istream.

A drawback of this approach is that one cannot set the maximum size of the resulting array. And that it reads the stream till its end.


If you need to read a fixed number of elements, then something like the following would do:

int arr[5]; // Need to read 5 elements.
for(auto& x : arr)
    if(!(std::cin >> x))
        throw std::runtime_error("failed to parse an int");
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
1

array variable always give base address of an array

for (int i =0;i<n;i++){
    cout<< array[i] << " ";
    cout<<*(array+i)<< " ";
}

Both cout statements will print same only. in short array[i] compiler will internally convert into *(array+i) like this only

in the second cout statement from base address of an array it won't add value,since it is an pointer it will add sizeof(int) each time for an increment

Gokulnath
  • 23
  • 1
  • 8