How to edit the text in a file

I have this basic coding below that will read the file and display it. I want to be able to change the formatting of the text in the file. For example the format the birthday is DD MM YYYY and I'm trying to slightly convert that to MM DD YYYY.

Also I am not trying to rewrite the file but rather make a new file with the changes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  #include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}
read the file into a vector, change the vector to whatever you wish, then write the vector back to a file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <vector>
#include <string>
#include <fstream>

//write vector to file spaced by index, separated by sep
void write(std::string filename, std::vector<std::string> v, std::string sep="\n"){
    std::ofstream f;
    f.open(filename);
    for (std::vector<int>::size_type i = 0; i != v.size(); i++) {
        f << v[i] << sep;
    }
    f.close();
}
//open file and read into vector str
std::vector<std::string> open(std::string filename){
    std::vector<std::string> v;
    std::ifstream f;
    f.open(filename);
    while(getline(f, s)){
        v.push_back(s);
    }
    f.close();
    return v;
}
Last edited on
while(getline(f, s)){
v.push_back(s);

s???
closed account (28poGNh0)
Can you give the content of the text file?
while(getline(f, s)){
v.push_back(s);

s???

yes the string s, is being appended to the vector string, then the vector with the entire file is being returned to the caller.

my example reading in my vim config file (in linux):
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
#include <iostream>
#include <vector>
#include <string>
#include <fstream>

std::vector<std::string> open(std::string filename){
    std::string s = "";
    std::vector<std::string> v;
    std::ifstream f;
    f.open(filename);
    while(getline(f, s)){
        v.push_back(s);
    }
    f.close();
    return v;
}

int main(){
    std::string path = "/home/metulburr/.vimrc";
    std::vector<std::string> lines = open(path);
    
    for (auto line:lines){
        std::cout << line << std::endl;
    }
}


at that point you can split the vector's elements or do whatever you want with it. modify it, etc. In your case swap the date format to american
Last edited on
Topic archived. No new replies allowed.