简体   繁体   中英

Reading space separated input into an array in 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.

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] << " ";
}

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");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM