Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading space separated input into an array in C++

Tags:

c++

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.

like image 482
J.Ren Avatar asked Nov 17 '25 11:11

J.Ren


2 Answers

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] << " ";
}
like image 200
Lincoln Cheng Avatar answered Nov 20 '25 04:11

Lincoln Cheng


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");
like image 31
Maxim Egorushkin Avatar answered Nov 20 '25 05:11

Maxim Egorushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!