Apr 6, 2013 at 3:08am UTC
Please look at the following code.
Can anyone tell me what the purpose of the cin.get(); (I bolded and underline it) in the function? If I delete cin.get(); , it skip the input for description.
Can someone explain to me in simple manner of what the purpose of the cin.get(); and why I need to include it in this function.
Thanks
void addRecord(fstream &invFile)
{
inventory record;
//open the file
invFile.open("invtry.dat", ios::out | ios::app | ios::binary);
//if error happen exit
if (invFile.fail())
{
cout << "Error opening binary file.\n";
exit(EXIT_FAILURE);
}
cin.get();
cout << "\nEnter the following inventory data:\n";
//get the description
cout << "Description: ";
cin.getline(record.desc, 31);
//get the quantity
cout << "Quantity: ";
cin >> record.qty;
while (record.qty < 0)
{
cout << "Enter a positive value, please: ";
cin >> record.qty;
}
//get the wholesale cost.
cout << "Wholesale cost: ";
cin >> record.wholeSale;
while (record.wholeSale < 0)
{
cout << "Enter a positive value please: ";
cin >> record.wholeSale;
}
//get retail price
cout << "Retail price: ";
cin >> record.retail;
while (record.retail < 0)
{
cout << "Enter a positive value please: ";
cin >> record.retail;
}
// get the date added to inventory
cout << "Date added to inventory: ";
cin >> record.date;
//write the record
invFile.write(reinterpret_cast<char*>(&record), sizeof(record));
//Make sure we didnt have error in writing
if (invFile.fail())
cout << "error writing record to file.\n";
else
cout << "record written to file.\n\n";
//close the file
invFile.close();
}
Apr 6, 2013 at 6:18am UTC
Probably it is here to skip newline symbol which can be left in input stream.
Best way to do this is to use ignore() method.