Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get user input from cin into C++11 std::array

Tags:

c++

arrays

c++11

How can I get input from the user into the std::array?

This is what I have but it will not compile.

std::array<char, 10> myArray{"hello"} ;
std::cout << "Enter your name: ";
std::cin >> myArray;

If more than 10 characters are entered, truncate and ignore them. I would also need the cin buffer cleared to allow for other input later on.

like image 245
dmaelect Avatar asked Mar 18 '23 11:03

dmaelect


1 Answers

For your current example you should use std::string instead of std::array<char, 10>. However, if you still want to read an array you could do it as follows:

#include <iostream>
#include <array>

int main() {
    std::array<int, 10> arr;
    for(int temp, i = 0; i < arr.size() && std::cin >> temp; ++i) {
        arr[i] = temp;
    }

    for(auto&& i : arr) {
        std::cout << i << ' ';
    }
}

Output:

$ ./a.out
10 11 12 13 14 15 16 17 18 19
10 11 12 13 14 15 16 17 18 19

The basic idea is to just loop over until the array size and then insert it into the array using its operator[]. You keep the std::cin >> temp in the loop condition to catch errors in the insertion process. Note that there isn't a built-in function in the standard library that does this for you.

If you do find yourself doing this often, you could move it into your own function:

#include <iostream>
#include <array>

template<typename T, size_t N>
std::istream& input_array(std::istream& in, std::array<T, N>& arr) {
    unsigned i = 0u;
    for(T temp; i < arr.size() && in >> temp; ++i) {
        arr[i] = std::move(temp);
    }
    return in;
}

int main() {
    std::array<int, 10> arr;
    input_array(std::cin, arr);
}

You shouldn't overload operator>> for things inside the std namespace since that's undefined behaviour.

If you want to avoid the temporary you could modify the function as follows:

template<typename T, size_t N>
std::istream& input_array(std::istream& in, std::array<T, N>& arr) {
    for(unsigned i = 0u; i < arr.size() && in >> arr[i]; ++i) { 
        // empty body
    }
    return in;
}
like image 75
Rapptz Avatar answered Mar 31 '23 19:03

Rapptz