The infile >> productQty[i]
and infile >> productPrice[i]
statements are reading int
/double
values and leaving the line breaks after them in the stream, to be read by the next std::getline()
call, which is not what you want to happen.
You need to either:
use std::getline()
to read every line, and then use std::istringstream
to parse the int
/double
values from their respective lines:
int ReadData(string productName[], string productLocation[], int productQty[], double productPrice[])
{
ifstream infile("prog1.txt");
int i = 0;
while (getline(infile, productName[i]))
{
getline(infile, line);
istringstream(line) >> productQty[i];
getline(infile, productLocation[i]);
getline(infile, line);
istringstream(line) >> productPrice[i];
++i;
}
infile.close();
return i;
}
call infile.ignore()
after reading the int
/double
values, to read and dismiss the line breaks:
int ReadData(string productName[], string productLocation[], int productQty[], double productPrice[])
{
ifstream infile("prog1.txt");
int i = 0;
while (getline(infile, productName[i]))
{
infile >> productQty[i];
infile.ignore(numeric_limits<streamsize>::max(), '\n');
getline(infile, productLocation[i]);
infile >> productPrice[i];
infile.ignore(numeric_limits<streamsize>::max(), '\n');
++i;
}
infile.close();
return i;
}
In either case, the arrays must be pre-allocated with enough elements to hold as many products as are in the file. Since the code has no way of actually verifying that count, I would suggest an alternative safer approach:
struct productInfo
{
string name;
string location;
int quantity;
double price;
};
istream& operator>>(istream &in, productInfo &out)
{
string line;
if (!getline(in, out.name)) {
// don't set failbit yet, in case this is just EOF...
return in;
}
// at this point, a new product is encountered, so
// any missing data is considered a failure...
if (!getline(in, line)) {
in.setstate(failbit);
return in;
}
if (!(istringstream(line) >> out.quantity)) {
in.setstate(failbit);
return in;
}
if (!getline(in, out.location)) {
in.setstate(failbit);
return in;
}
if (!getline(in, line)) {
in.setstate(failbit);
return in;
}
if (!(istringstream(line) >> out.price)) {
in.setstate(failbit);
return in;
}
return in;
}
int ReadData(vector<productInfo> &products)
{
ifstream infile("prog1.txt");
int i = 0;
productInfo info;
while (infile >> info)
{
products.push_back(info);
++i;
}
infile.close();
return i;
}