views:

303

answers:

3

I've been working on getting this program complete where it saves multiple structs to a file, can read them back and edit them, then save them all back to a file. I've been working on the logic of this not to mention lots of help from others and a ton of googling hours... now I am getting a compile error. Any help would be very appreciated.

Code:

template<typename T>
void writeVector(ofstream &out, const vector<T> &vec);

struct InventoryItem {
    string Item;
    string Description;
    int Quantity;
    int wholesaleCost;
    int retailCost;
    int dateAdded;
} ;


int main(void)
{
    vector<InventoryItem> structList;
    ofstream out("data.dat");
    writeVector( out, structList );
    return 0;
}

template<typename T>
void writeVector(ofstream &out, const vector<T> &vec)
{
    out << vec.size();

    for(vector<T>::const_iterator i = vec.begin(); i != vec.end(); i++)
    {
        out << *i; //  error C2679
    }
}

Compiler error:

1>.\Project 5.cpp(128) : error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const InventoryItem' (or there is no acceptable conversion)
// listed overload variants skipped
1>        while trying to match the argument list '(std::ofstream, const InventoryItem)'
1>        .\Project 5.cpp(46) : see reference to function template instantiation 'void writeVector<InventoryItem>(std::ofstream &,const std::vector<_Ty> &)' being compiled
1>        with
1>        [
1>            _Ty=InventoryItem
1>        ]
A: 

You're trying to use the << operator for your struct, but that operator isn't defined for that type. Try outputting specific data members instead.

Kalium
Wait... what do you mean? Could you provide a short example ? Sorry!
OneShot
Something like `out << *i.Item` instead of `out << *i`.
Kalium
+8  A: 

You have no operator<< defined that would specify how your InventoryItem should be printed to an output stream. You try to print it and the compiler doesn't know how. You need to define a function like this one:

std::ostream& operator<<(std::ostream &strm, const InventoryItem &i) {
  return strm << i.Item << " (" << i.Description << ")";
}
sth
A: 

The << operator is defined as "shift bits left".

The IO classes override this operator and define << to mean print this structure.

When the compiler sees an integer item on the right side it assumes you mean the "shift bots left" and is looking for an intger on the left side but finds an IO stream object instead.

Try expiciltly converting the integer value to string before sending it to the stream.

James Anderson
both sides are evaluated. it's perfectly fine to insert int's into streams - e.g: std::strstream str;str << int(5);
qwerty