Validating line of data from file using string member functions.

Hello,

I'm having an issue wrapping my head around going about this. I have to read multiple lines of products in a file set up in this form into a struct array:

4011 BANANAS 1 0.49 123.2
(string of ints) (string) (int) (double) (double)

Now, if a part of the line is incorrect, like if the first part has a character or anything else then an int in the string, I'm supposed to skip the line completely.

I imagine I have to write an if statement within my while statement as I'm reading the data..any help would be appreciated.

Here's what I have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
bool readInvetory(string filename)
{
	//Open the file

	ifstream productsFile;
	productsFile.open("products.txt");

	//Error check if file does not open, exit program.

	if (!productsFile.is_open())
	{
		cout << "Error! Could not open file. Exiting program.";
		system("pause");
		exit(1);
	}

	//Create the dynamic array;

	Product* productInfo = new Product[MAXPRODUCTS];
	
	//Read the data from the file into the array

	if (productsFile.is_open())
	{
		string line;
		int index = 0;
		while (getline(productsFile, line))
		{
			if (/* ?????? */);
			productsFile >> productInfo[index].pluCode >> productInfo[index].nameOfProduct >>
				productInfo[index].salesType >> productInfo[index].productPrice >>
				productInfo[index].inventorylevel;
		}
}
Last edited on
Read line from the file one at a time.
Create a string stream from the line.
Attempt to parse the line into a temporary Product struct.
If parsing succeeds, copy the temporary Product into your array.
else maybe print a warning message saying that the line was skipped.
Topic archived. No new replies allowed.