0

I need to merge two text files by putting them in a vector array and then writing them in a new text file. After merging them.The new file has extra characters.

FE:

f1.txt ("text1")
f2.txt ("text2.")
f12.txt ("text1˙text2.˙W64")

Content of the buffer: "text1 text2. W64"

Here is the code:

int main(){
       enum errorcode{FNF,FNC};
       vector<char> buffer;
       char ime[255];
       cin>>ime;//first file
       ifstream ud1(ime,ios::in);
       if(ud1.is_open()){
                        while(!ud1.eof())buffer.push_back(ud1.get());
                        ud1.close();
                        }
       else {cout<<"File not found.";return FNF;}
       cin>>ime;//second file
       ifstream ud2(ime,ios::in);
       if(ud2.is_open()){
                         while(!ud2.eof())buffer.push_back(ud2.get());
                         ud2.close();
                         }
       else {cout<<"File not found.";return FNF;}
       cin>>ime;//new file
       ofstream id(ime,ios::out);
       if(id.is_open()){
                        for(int i=0;i<buffer.capacity();i++)id.put(buffer[i]);
                        id.close();
                        }
       else {cout<<"File not created.";return FNC;}
       return 0;

       }

I guess this is because of notepad or files themselves. Can you please tell me reason for this.

pajser
  • 1
  • 1
  • 2
  • 1
    I think `id << ud1.rdbuf() << ud2.rdbuf();` after validating all three files opened successfully would shorten this up quite a bit. And regardless, using `.eof()` id your loop conditions [**is wrong**](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – WhozCraig Jan 21 '15 at 07:26

1 Answers1

0

you are using Vector capacity: Returns the size of the storage space currently allocated for the vector, expressed in terms of elements.

You must use vector size: Returns the number of elements in the vector. This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity.

About the ˙

please look at istream::get return value:

Return Value

The first signature returns the character read, or the end-of-file value (EOF) if no characters are available in the stream (note that in this case, the failbit flag is also set).

So, you could change the loop to this:

while(!ud1.eof()){
    int tmpChar = ud1.get();
    if( !ud1.eof() )
        buffer.push_back(tmpChar);
}
Lucian
  • 3,118
  • 18
  • 18
  • Thanks for the imput. After changing capacity to size, the W64 is gone but ˙ remain between and at the end od texts. – pajser Jan 21 '15 at 07:24