Search code examples
c++clangistream

istringstream and reading float


This problem was also mentioned by this question.

I am reading a file line by line with std::getline.

     std::getline(points_file, thisline);
     std::istringstream iss(thisline);
     int cnt = 0;
     Coordinates.resize(NumberOfNodes, std::vector<float>(3));
     for(std::istream_iterator<float> iit( iss );
        iit!=std::istream_iterator<float>( );
        iit++ )
     {
        assert( cnt < 3 );
        *(iit) >> Coordinates[i][cnt];
        cnt++;
     }

The error message : error: invalid operands to binary expression ('const float' and 'std::__1::__vector_base<float, std::__1::allocator<float> >::value_type' (aka 'float')) *(iit) >> Coordinates[i][cnt];

If I try to read integers instead this works perfectly. I am using CLANG. It seems like this problem does not occur with GCC however, I don't have access to this atm to actually test. Also, why would CLANG fail on this and how could it be resolved?


Solution

  • Use push_back or a regular assignment (not >>) to store values in your container:

    for(std::istream_iterator<float> iit(iss), iitEnd; iit != iitEnd; iit++)
    {
       assert( cnt < 3 );
    
       // This means you SHOULDN'T pre-resize()
       Coordinates[i].push_back(*iit);
    
       //or
    
       // This means you SHOULD pre-resize()
       Coordinates[i][cnt] = *iit;
       cnt++;
    }
    

    Also, consider using something like:

    using vec3 = std::array<float, 3>;
    

    instead of std::vector<float>(3) for both performance and safety.