0

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;

}

reimotaavi
  • 57
  • 6
  • 1
    You should write a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example), including the code you tried, the input and expected output. – anastaciu Apr 07 '20 at 14:37
  • 1
    https://stackoverflow.com/q/388242/4386278 – Asteroids With Wings Apr 07 '20 at 14:37
  • In most cases one does not rewrite things in a file *in-place* unless the file has fixed size fields. Instead, one writes the data to a *new* file and then atomically renames it to the original file name. – Jesper Juhl Apr 07 '20 at 14:38
  • Do you *really* need to store the entire file into memory? Most applications only read in a portion, or chunk of a file at a time, including editors. – Thomas Matthews Apr 07 '20 at 17:17
  • I can't just change the first line in text file. I need to rewrite everything – reimotaavi Apr 07 '20 at 17:27

1 Answers1

1

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]
}
Samuel
  • 315
  • 3
  • 14