cin.ignore() to skip \n intermittently fails

Below is the beginning of a C++ program that uses fstream to write a structure to a binary file.

I have tried to use cin.ignore() to skip over newline chars that are causing cin reads to be skipped. It worked for several runs, followed by persistent failure.

In case it helps to know. The total project has the following specifications:

Must use a structure to store the following inventory data in a file:

item description
qty on hand
wholesale cost
retail cost
date added to inventory

will eventually use 3 separate functions to:

add records, display a requested record, change any record.


thanks in advance.




#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>


using namespace std;

const int DESC_SIZE = 15;
const int DATE_ADDED_SIZE = 8;

// declare a structure for an inventory record
struct InventoryRecord
{
char desc[DESC_SIZE];
int qtyOnHand;
double wholesaleCost;
double retailCost;
char dateAdded[DATE_ADDED_SIZE];
};

int main()
{
InventoryRecord invRec; // to hold inventory record
char choice = 'n'; // to hold response Y or N

// open a file for binary output.
fstream invFile("products.dat", ios::out | ios::app |ios::binary);

do
{
// get data about a product
cout << "Enter Inventory Data:\n\n\n";

cout << "Product Description: ";
cin.getline(invRec.desc, DESC_SIZE);
cout << endl;

cout << "Quantity On Hand: ";
cin >> invRec.qtyOnHand;
cin.ignore(); // skip remaininng newline char
cout << endl;

cout << "Wholesale Cost: ";
cin >> invRec.wholesaleCost;
cout << endl;

cout << "Retail Cost: ";
cin >> invRec.retailCost;
cout << endl;

cin.ignore(); // skip remaininng newline char

cout << "Date Product Added to Inventory:";
cin.getline(invRec.dateAdded, DATE_ADDED_SIZE);
cout << endl;

//Write the contents of the person structure to the file.
invFile.write(reinterpret_cast<char *>(&invRec),
sizeof(invRec));

cout << "Do you want to enter another record? ";
cin >> choice ;
cout << endl; // ?? without this endl a cin.ignore() is needed. yea!

} while (choice == 'Y' || choice == 'y');

invFile.close();


}
Please use code tags when posting code.

You seem to have a lot of unnecessary endl, and ignore() statements in your code, but you seem to be missing ignore() in a couple of key places.

First the only places you should need the ignore() is before the getline() for dateAdded and right before and directly after the cin >> choice; line.

You really shouldn't need the endl anywhere in this function, unless you actually want a blank line between all of your entries.

Thanks for the help.

I didn't read carefully. It appears that if I had pasted between the two tags my code would have been readable.

Is that all there is to it?

Richard
Last edited on
For comments: out on the right side you see a few buttons one of the looks like this: "<>", Click on this one and put your code inside of those tags.
Last edited on
Topic archived. No new replies allowed.