store data from file

I need to read and store data from file.
The file has the following format: name size vote.

What is the best way to store this data, so later I need to calculate total size for all names and total votes?

Is it possible to use a vector for this? I am not sure how, does it need to be 3D vector? Thanks!


Yes you can use a vector for this, simply declare 3 vectors, one for names, one for size, and one for vote. This is probably the simplest way to do it.

as for reading and writing to the file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<fstream>
#include<string>
using namespace std;

int main() {
       string name("John");   //assuming it is string
       int size = 5;                 //assuming it is int
       bool vote;                   //assuming it is bool

      ofstream oFile("file.txt");
      file << name << ' ' << size << ' ' << vote << endl;    //writing to file
      oFile.close();
      
      ifstream iFile("file.txt");
      file >> name >> size >> vote;                     //reading from file
      iFile.close();
      
      return 0;
}


Well, I don't know how well this code works, cause I haven't coded quite a long time...but I think it gives the general idea.
Last edited on
here is what I have so far, is this a good way to put it?

Thanks.

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
struct Items
{
  string name;
  int size, votes;

};


int main()
{
vector<Items> it;
Items item;
ifstream infile("packets.txt");
  	if (!infile)
	{
		cout << "Error opening the file. \n";
	}

  	while (infile.good())  
	 {
		
      	infile >> item.name >> item.size >> item.votes;
		it.push_back(item);
	}
	
   infile.close();
   for (int i =0; i<4; i++)
   {
	 cout <<  it[i].name << " " << it[i].size << " " << it[i].votes << "\n";
   }

   return 0;
  } 
Last edited on
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
struct Items
{
  string name;
  int size, votes;

};


int main()
{
vector<Items> it;
Items item;
ifstream infile("packets.txt");
  	if (!infile)
	{
		cout << "Error opening the file. \n";
	}

  	while (infile.good())  
	 {
		
      	infile >> item.name >> item.size >> item.votes;
		it.push_back(item);
	}
	
   infile.close();
   for (int i =0; i<it.size(); i++)  //just changed here
   {
	 cout <<  it[i].name << " " << it[i].size << " " << it[i].votes << "\n";
   }

   return 0;
  } 


I assume you have the appropriate #include<> 's.

I suggest you indent it properly too.

Other than that, its fine. ;)
Topic archived. No new replies allowed.