Hello again!
I am working on a project for a few days,and it seems i've ended up in a dead end just when i was about to finish it.Here's is the code so i can explain my problem.
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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
|
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
#include <cstdlib>
using namespace std;
void saveTofile (vector <string> v);
int readFromFile (vector <string> &v , int &i,string line);
void show (vector <string> v);
int main()
{
ofstream myfile ("data.txt");
vector <string> v;
string line;
int i = 1 ;
while(line != ":q")
{
cout << i << "> ";
getline (cin , line);
if ( line.at(0) == ':' )
{
if ( line.at(1) == 'c' )
{
v.clear(); //clears vector
i = 1;
}
else if ( line.at(1) == 's' )
{
show(v); //shows vector
}
else if ( line.at(1) == 'd' )
{
int k ;
k = atoi(line.substr(3).c_str()); // char--> int
v.erase( v.begin() + (i+1) , v.begin()+ (i+k) ) ; //erases the vector
i++;
}
else if ( line.at(1) == 'w')
{
saveTofile (v); //saves the vector
}
else if (isdigit(line.at(1) ) )
{
i = atoi (line.substr(1).c_str()) ; //jumps to line given by the user
}
else if (line.at(1) == 'i')
{
readFromFile (v,i,line); //inserts lines from txt file
}
else if ( line.at(1) == 'a')
{
i=v.size(); //changes current line to last line
}
}
else
{
v.push_back(line); //inserts line in vector
i++;
}
}
system("PAUSE");
return 0;
}
//function for saving vector to file
void saveTofile (vector <string> v)
{
ofstream myfile ("data.txt");
for (int n = 0 ; n < v.size(); n++)
{
myfile << v[n] << endl;
}
}
//function for reading file to vector
int readFromFile (vector <string> &v,int &i , string line)
{
ifstream myfile (line.substr(3).c_str());
char s[256];
int oldVsize = v.size();
while (!myfile.eof())
{
if (i<=oldVsize)
{
myfile.getline(s,256);
v.insert (v.begin()+i , oldVsize-i,s);
i++;
}
else
{
myfile.getline(s,256);
v.push_back (s);
}
}
i=v.size();
myfile.close();
}
//function for showing vector
void show( vector <string> v)
{
for(int i=0; i < v.size(); i++)
{
cout << i + 1 << "> " << v[i] << endl;
}
}
|
The problem is with the function readFromFile,where i couldn't do anything better than that...
The description of the command is: (:i filename) to insert the lines of the file.If current line is i and the filename has m lines,then the lines from n to n+m-1 contain the filename data, while the previous contents of the lines n,n+1,n+2,.. , have moved to n+m,n+m+1,n+m+2.After the completion of the function,current line should be line (n+m).
I should point out that we suppose the commands are always correct,so there will be no need to check it.The commands also don't have to be saved in the vector.