#include <iostream>
#include <fstream>
#include <sstream>
usingnamespace std;
void display(string &rec)
{
int code;
string name;
float price;
char del;
// the istringstream object receives the string
// and separates it to its fields(code, label, price)
istringstream iss(rec);
iss >> code;
iss >> del;
iss >> name;
iss >> del;
iss >> price;
// display the fields of the record
cout << "**************************\n";
cout << "code: " << code << endl;
cout << "label: " << name << endl;
cout << "price: " << price << endl;
cout << "**************************\n";
return ;
}
int main()
{
bool more = 1;
ifstream fin;
ofstream fout;
string record;
int code; string name; float price; // the field of the record
fout.open("data.txt", ios_base::app);
while(more)
{
// the user enters the fields of the record
// code, label, price
cout << "Enter code: ";
cin >> code;
cin.ignore();
cout << "Enter label: ";
getline(cin, name);
cout << "Enter price: ";
cin >> price;
// takes the fields and unites them in
// a string that should have the structure:
// field1,field2,field3
ostringstream oss(ostringstream::trunc);
oss << code << "|" << name << "|" << price << endl;
record = oss.str();
// the record as as string is now written in the file
fout << record;
cout << "Enter another?";
cin >> more;
}
fout.close();
fin.open("data.txt");
while (!fin.eof())
{
// read the record from the file
getline(fin, record);
// display them
display(record);
}
fin.close();
return 0;
}
I have a problem in the display function!
The istringstream obj is supposed to read each
field of the record and store them in their
respective variables!
But this only works for the code field.
When it reads the name field it reads the price field too!
For example a here is a sample run:
Enter code: 147
Enter label: ruffles
Enter price: 1.75
Enter another?0
**************************
code: 147
label: ruffles|1.75
price: -1.07374e+008
**************************
Why this is happening and how can i fix it?
Any help would be appriciated!