Hello All,
This is a student assignment. So I don't want the complete answer just a hint or maybe a bumb on the head cause I'm doing it the wrong way. Assume I haven't done anything braindead like not include a header etc... I can post the whole code if you like/need it but I'm trying to spare the forum :)
Got a product structure...
-
struct product {
-
string id;
-
string description;
-
int quantity;
-
double wholesale;
-
double retail;
-
Date* date_added;
-
};
-
Got a vector of products and a file for the data...
-
vector<product> Inventory;
-
ifstream inFile; //Input data file
-
ofstream outFile; //Output report file
-
Saved all the products to a tab delimited file, one product to each line using for_each...
-
-
for_each(Inventory.begin(), Inventory.end(), save_product(&outFile));
-
-
class save_product:public std::unary_function<product, bool>
-
{
-
private:
-
ostream* m_os;
-
public:
-
save_product( ostream* os ){ m_os = os; }
-
bool operator()( const product& element )
-
{
-
bool ret_val = false;
-
// save element in tab delimited format
-
*m_os << element.id.c_str()
-
<< "\t" << element.description.c_str()
-
<< "\t" << element.quantity
-
<< "\t" << element.wholesale
-
<< "\t" << element.retail
-
<< "\t" << element.date_added->get(2) // write date in month/day/year format
-
<< "/" << element.date_added->get(1)
-
<< "/" << element.date_added->get(3)
-
<< "\r\n";
-
if(m_os)
-
ret_val = true;
-
return ret_val;
-
}
-
};
-
No problem so far. The file is as I want it. But getting the data back into the vector is causing me some problems. I've seen the use of the copy algorithm for copying from a fstream to a vector but I need to tell the iterator to use tabs to delimit the text.... I wrote a functor load_product but what algorithm could I use to read the file in with...
-
-
// Copy doesn't quite do what I want with data...
-
copy( istream::iterator<T>(inFile), istream::iterator<T>(), back_inserter(Inventory) );
-
-
class load_product:public std::unary_function<product, bool>
-
{
-
private:
-
istream* m_is;
-
public:
-
load_product( istream* is ){ m_is = is; }
-
bool operator()( product& element )
-
{
-
bool ret_val = false;
-
char buffer[maxStringSize];
-
stringstream ioConv;
-
unsigned int fieldCnt = 0;
-
-
while(m_is && fieldCnt < REC_FIELD_COUNT )
-
{
-
m_is->getline(buffer,(streamsize)maxStringSize, '\t');
-
if(m_is)
-
{
-
switch( fieldCnt )
-
{
-
case 0: element.id = buffer; break;
-
case 1: element.description = buffer; break;
-
case 2: ioConv >> buffer; ioConv << element.quantity; break;
-
case 3: ioConv >> buffer; ioConv << element.retail; break;
-
case 4: ioConv >> buffer; ioConv << element.wholesale; break;
-
default:
-
element.date_added->set(buffer, "/");
-
break;
-
}
-
}
-
fieldCnt++;
-
if( fieldCnt == REC_FIELD_COUNT && m_is ) ret_val = true;
-
}
-
-
return ret_val;
-
}
-
};
-
-
I can do this manually with a while sure but I was hoping for a more elegant/STL way of doing it...
Thanks for any guidance...
John