Reputation: 57
I have a text file where I need to be able to add or delete certain lines using functions. Everything is read from the file so when I open the file and write something then it deletes everything else in that file. I've understood that this can be done by using vectors. As I am new to C++ and especially vectors, I haven't figured out how I can read every line to a vector and then rewrite the lines to the text file. Maybe someone can recommend me some kind of web-page or sth where I could learn how to do it.
Function for adding a line so far but it does not add the new line.
It should read the existing lines in the text file to vector<string> lines
and then output it to the file while ignoring the first line with lines[i+1]
and then add the new contact info to the end outside of the for loop.
void add contact(string filename, string*& names, string*& emails,
string*& numbers, unsigned int& quantity, string name, string email,
string number){
string str;
vector<string> lines;
ifstream input(filename);
while(getline(input, str)){
lines.push_back(str);
}
input.close();
ofstream output("contacts.txt");
output << quantity;
for(unsigned int i = 0; i < quantity; i++){
output << endl << lines[i+1];
}
output << endl << name << " | " << email << " | " << number << endl;
}
Upvotes: 0
Views: 2133
Reputation: 314
It's not that tough. You just have to get each line and push it to the std::vector.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main()
{
std::string str ;
std::vector<std::string> file_contents ;
std::fstream file;
file.open("test.txt",std::ios::in);
while(getline(file, str))
{
file_contents.push_back(str) ;
}
// You can access it using vector[i]
}
Upvotes: 1