dimanche 8 janvier 2023

Overloading operator>> to create array from string

I would like to create an std::array from a std::string.

For this, I would like to overload the operator>>.

I have the following test case:

std::istream& operator>>(std::istream& is, const std::array<double, 3>& a)
{
    char p1, p2;

    is >> p1;
    // if fail warn the user

    for (unsigned int i = 1; i < a.size(); ++i) 
    {
        // something to ignore/ check if numeric
    }

    is >> p2;
    // if fail warn the user
    
    return is;
}

int main()
{
    std::string a = "[1 2 3]";
    std::array<double, 3> arr;
    std::istringstream iss (a);
    iss >> arr;
    
    return 0;
}

I would like for the operator to check if the characters [and ] are in the correct place and to construct the array with the elements inside.

How can I do checks if the extraction was successfull? How can I check the string between the parenthesis is numeric and if so construct my array from it?

Kind regards

Aucun commentaire:

Enregistrer un commentaire