user2917559
user2917559

Reputation: 163

In C++, how to read the contents of a text file, and put it in another text file?

I want to read the contents of a input.txt file and put it in the output.txt file, I tried to do this in the below code, but I was not successful, I am new to C++ file operations, can you tell me how to do this ?

   #include <iostream>
   #include <fstream>
   #include <string>
   #include <vector>
     using namespace std;

    int main () {
     string line;
     std::vector<std::string> inputLines;
      ifstream myfile ("input.txt");
    if (myfile.is_open())
    {
       while ( getline (myfile,line) )
    {
         cout << line << '\n';
        inputLines.push_back(line);  
    }
     myfile.close();
    }

    else cout << "Unable to open file"; 

    ofstream myfile2 ("output.txt");
    if (myfile2.is_open())
    {
     for(unsigned int i = 0;i< inputLines.size();i++)

  myfile2 << inputLines[i];

      myfile2.close();
    }

    return 0;
     }

Upvotes: 1

Views: 1845

Answers (2)

Semih Ozmen
Semih Ozmen

Reputation: 591

In your code you are not storing the input lines. First, define a vector of strings by

std::vector<std::string> inputLines;

and store each input line into your list with

inputLines.push_back(line)

and then write your input lines to output by looping over the items of the vector with

for(unsigned int i = 0;i < inputLines.size();i++)
 myfile2 << inputLines[i]

PS:you may need

#include <vector>

Upvotes: 3

Sebastian Negraszus
Sebastian Negraszus

Reputation: 12195

You must call myfile2 << line; inside the while loop.

Upvotes: 2

Related Questions