vector that grows and shrinks

OK, so I need to create a vector that shrinks and grows as the user processes the transactions from a input data file called "data3.txt" Transaction file can only include three commands, Insert, delete, Print.
-Insert command, you get two more information, information you need to insert and the position it should be inserted.
-Delete command, you get one more information that indicates which element(index) should be deleted
-Print command prints the content of the vector on the screen

Here's the input file "data3.txt":
Insert Normality 0
insert Perfection 1
Insert programs 1
Print
Insert perfection 5
Delete 1
Delete 7
Insert Cash 3
Delete 4
Print



Here's what I got, it isn't much, but I think the main function has the right idea, I just need help with the three functions, any help, examples, tips on how to do this function is much 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
#include <iostream>
#include <vector>
#include <ifstream>
using namespace std;

void Delete()
{

}

void Insert(int v, )
{
  V.insert( )
}

void Print(vector<string>& v)
{
  for(int i = 0; i < v.size(); i++)
  {
    cout << v[i] << " ";
  }
}

int main()
{
  vector<string> V;
  string cmd, wd;
  int pos;

  ifstream fin;
  fin.open("data3.txt");

  if(!fin)
    cout << "The file doesn't exist " << endl;
  else //The file exists
    {
      while(!fin.eof())
        {
          fin >> cmd;

          if(cmd == "Insert")
            {
              fin >> wd;
              fin >> pos;
              Insert(V, wd, pos); //Function call
            }
          else if(cmd == "Delete")
            {
              fin >> pos;
              Delete(V, pos);
            }
          else
            {
              Print(V);
            }
        }
    }

  return 0;
}
I think the main function has the right idea,

The only obvious error in main() is the wrong while loop

replace

1
2
3
 while(!fin.eof())
        {
          fin >> cmd;

with
1
2
 while(fin >> cmd)
 {


As written now, you're calling Print(V) one extra time after the end of file is reached.

Style could be improved (what are pos and wd doing all the way in the beginning of main?), and you could process the file line by line rather than word by word, to be able to report more syntax errors, but otherwise it's okay.

I just need help with the three functions

Insert can call V.insert() directly, see http://www.cplusplus.com/reference/stl/vector/insert/

Delete() can call V.erase(V.begin()+pos), see http://www.cplusplus.com/reference/stl/vector/erase/

What do you plan to do if the position passed to Delete() does not exist?
Last edited on
Somehow I need to be able to check if the insert is possible, should be able to delete if the size is not beyond of the vector
Pos=position and wd=word
Last edited on
Topic archived. No new replies allowed.