Problem with reading a file into array of struct

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

struct inventory
{
    int barcode;
    char description[512];
    float price;
    int quantity;
};


int main()
{
    cout << fixed;
    cout << setprecision(2);

    inventory s[4];

    char filename[128];
    ifstream infile;
    cout <<"Enter the file name : ";
    cin.getline(filename, 128);
    infile.open(filename);

        while (!infile)
        {
        cout << "File could not be opened"<<endl;
        cout <<"Enter the file name again :";
        cin.getline(filename, 128);
        infile.open(filename);
        }



        while (!infile.eof())
        {
            if (!infile.eof())
            {
            for(int i = 0; i < 4; i++)
            {
            infile >> s[i].barcode;
            cin.ignore();
            infile.getline(s[i].description, 512);
            infile >> s[i].price;
            infile >> s[i].quantity;
            }
            }
        }



        for(int i = 0; i < 4; i++)
        {
        cout << "barcode : " << s[i].barcode << endl;
        cout << "description : " << s[i].description << endl;
        cout << "price : " << s[i].price << endl;
        cout << "quantity : " << s[i].quantity << endl;
        cout << endl;
        }



        return 0;
}



This is my text file
20123451
Sugar packet (1 kg)
2.50
560
21347652
Milo 3-in-1 
12.50
200
20123453
Salt (1kg)
4.50
270
21347654
Nescafe 3-in-1
12.50
400
20123455
Tamatoes
4.00
100
21347656
Cucumbers
4.00
280


This is my program output
Enter the file name : "filename".txt
..... (Nothing shows up)


Any help would be greatly appreciated.
Last edited on
1
2
infile >> s[i].barcode;
cin.ignore();
You are reading from infile, but ignoring character from cin.
use this:
1
2
infile >> s[i].barcode >> std::ws; //ignore was not created for that
cin.ignore();

Also looping on eof() is bad idea. Depending on quirks of your text editor you can have a problem later.
Topic archived. No new replies allowed.