String concatenation

Hi i am new to programming and trying to write a simple program which is able to read the txt file line by line and append e3 at the end of each line. Can anyone help me in this pgm?
Can you post your current progress?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <string>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
  vector<string> text_file;

  ifstream ifs( "data.txt" );
  string temp;
  for (int i=0; i<temp; i++)
  			file << temp << "e3 "<<endl;

  while( getline( ifs, temp ) )
     text_file.push_back( temp );
}
You're using the string class, so you can concatenate using the += operation.

Example,
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 <fstream>
#include <string>
#include <vector>
#include <iostream>

int main()
{
   ifstream in_file("data.txt");
   string temp;
   vector <string> str_list;

   if (in_file.is_open())
   {
      while (in_file.good())
      {
         getline(in_file, temp);   // Assign line to temp
         temp += "e3";             // String concatenation
         str_list.push_back(temp); // Push string to vector
      }
   }
   else
      cout << "Unable to open file\n";

   return 0;
}


Hope this helps.

Last edited on
Thanks for the help, but the program is terminating without and errors or warning. Nothing has changed in my txt file
Oh, sorry. I misunderstood - you want the appended strings to be put back into a text file.

You can add this before the return. Beware, giving it the same name as your input file will overwrite it. If you want a separate file, give it a different name.

1
2
3
4
5
6
7
8
9
10
11
12
ofstream out_file ("data.txt");

if (out_file.is_open())
{
   for (int i=0; i < str_list.size(); i++)
   {
       out_file << str_list[i] << "\n";
   }
   out_file.close()
}
else
   cout << "Couldn't open output file\n";
Thanks it was able to do the job :)
Topic archived. No new replies allowed.