reading from a file into a struct

I am trying to read some data into a struct from a file, but I keep getting an error for infile >> whInventory[i].itemName; The data I'm reading is a file filled like
1235 itemName
2345 itemName2

I am also getting an infinite loop for my .eof() function. Why does that happen?

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

#include<iostream>
#include<cstring>
#include<fstream>

using namespace std;


struct ItemRec   
{
	string wareHouse;
	int itemNbr;
	string itemName;
	int quantity;
	float wholesalePr;
	float markup;
	float retail;
};





int main()
{
	ItemRec  whInventory[150];
	ifstream infile;
	int i = 0;
	int a;
	infile.open("WLL1.txt");

	infile >> whInventory[i].itemNbr;
	while (!infile.eof())
	{
                infile >> whInventory[i].itemNbr;
		infile >> whInventory[i].itemName;
		

		i++;
	}



	for (int x = 0; x <= i; x++)
	{
		cout << whInventory[x].itemNbr;
		cout << whInventory[x].itemName << endl;
	}



	return 0;
}
Last edited on
You need to check infile to see if it really opened, before your while loop.

If your data is stored number name, then you need to switch lines 35 and 36.
The file does open. That is a typo on the lines 35 and 36 they are switched in my code.
the cstring was the problem it should be just string. Thanks for the input though
Something strikes as odd in this code fragment:

1
2
3
4
infile >> whInventory[i].itemNbr;
	while (!infile.eof())
	{
                infile >> whInventory[i].itemNbr;


You load a different number into itemNbr after you previously store a number into it. Is that the correct usage you want?
Topic archived. No new replies allowed.