1 Write a program that creates a vector of string called Vec

1)      Write a program that creates a vector of string called “Vec”. Vector “Vec” grows and shrinks as the user processes the transactions from a data file called “Transaction.txt”. The transaction file can only include three types of commands: Add, Remove, and Print. With “Add” command, you get two more information, the information you need to put into the vector and the position the information should be inserted. With “Remove”, you get one more information that indicates which element (index) should be deleted. Print command means the content of the vector should be printed on the screen. For example, you may have the following information in your file:

Add                 Hello               4

Remove                                   5

Print

The first line indicates that the word “Hello” should be located in the forth index which means Vec [4]. Of course you should check if this insert is possible. This insert is possible if the position you are attempting to insert the element is not beyond the size of the vector. The second line means Vec [5] should be removed. Again this operation should only be allowed if the index is not beyond the current size of the vector. Test your program with the following Transaction file:

Add     Student            0

Add     Kid                  0

Add     Final                1

Add     Grow               1

Add     Note                2

Print

Add     Rich                 5

Remove                       1

Remove                       7

Add     Mind               2

Remove                       3

Print

Solution

PROGRAM CODE:

/*
* basics.cpp
*
* Created on: 01-Feb-2017
* Author: kasturi
*/

#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

vector<string> vec(20);
vector<string>::iterator it;

int main() {
ifstream infile(\"Transaction.txt\");
string line;
while(getline(infile,line))
{

istringstream iss(line);
string command;
iss>>command;
if(command == \"Add\")
{
string word;
int position;
iss>>word>>position;
vec.insert(vec.begin() + position, word);
}
else if(command == \"Remove\")
{
int position;
iss>>position;
vec.erase(vec.begin() + position);
}
else if(command == \"Print\")
{
for (vector<string>::const_iterator i = vec.begin(); i != vec.end(); ++i)
{
if(*i != \"\")
{
cout << *i << \"\ \";
}
}

}

}
return 0;
}

OUTPUT:

Kid

Grow

Note

Final

Student

Kid

Note

Mind

Student

Rich

1) Write a program that creates a vector of string called “Vec”. Vector “Vec” grows and shrinks as the user processes the transactions from a data file called “
1) Write a program that creates a vector of string called “Vec”. Vector “Vec” grows and shrinks as the user processes the transactions from a data file called “

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site