vector of structs help

I am trying to store a text file that contains 3 columns ( unsigned int/ string /float) of 57 rows into a vector that holds a struct of 'items'. With my code written I am able to store and print out the first line given in the text file.
I have been messing around w/ the push_back function of vector but seem to be implementing it incorrectly. Desired output is to have a vector that is 57 elements in length each holding a struct 'item' containing the 3 different variables of unsigned int / string / float. Any help is appreciated.

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
68
69
70
71
72
73
74
  using namespace std;
#include <cstdlib>
#include <vector>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>

struct item{

        unsigned int barcode;
        std::string item_name;
        float price;
};

struct cart_item{
        unsigned int barcode;
        std::string item_name;
        float price;
        int quantity;
        float item_total;
};


int main()
{





        vector<item> balla;

         vector<char *> dataFromFile;
        char *cstr;

        ifstream file("inventory.txt");

        if(file.is_open())
        {
                do
                {
                        cstr = (char *)malloc(256);
                        file.getline(cstr, 256);
                        dataFromFile.push_back(cstr);
                }
                while(!file.eof());
                cout << "File successfully read" << endl;
        }
        else
                cout << "Failed to open file" << endl;



        vector<char *> items;
        char *pChar;

        pChar = strtok(dataFromFile[0], "|");
        while (pChar != NULL)
{
            items.push_back(pChar);
            pChar = strtok (NULL, "|");
        }

        item entry[57];


        entry[1].barcode = atoi(items[0]);
        entry[1].item_name = items[1];
        entry[1].price = atof(items[2]);

        items.push_back(entry);

        cout << items[0] << items[1] << items[2] << endl;
You created items as vector of chars, but in line 72 you try to push to it entry, which is not a char. What you should do is to make a loop that will go as many times as needed, in your case: 57, and inside create an item for each line of text:

1
2
3
4
5
6
7
8
9
vector<item> items;
for(int i = 0; i < dataFromFile.length(); i++) {
    item entry;
    entry.barcode = /*Extract Barcode from dataFromFile[i]*/;
    entry.item_name = /*Extract Name from dataFromFile[i]*/ ;
    entry.price =/*Extract Price from dataFromFile[i]*/;
    items.push_back(entry);
    cout << items[i].barcode << items[i].item_name.c_str() << items[i].price << endl;
}
Last edited on
thank you
Topic archived. No new replies allowed.