1

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;
     }
user2917559
  • 163
  • 1
  • 2
  • 12

2 Answers2

3

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>
Semih Ozmen
  • 571
  • 5
  • 20
  • Thank you, in the above program, i am reading the contents line by line, can you please tell me how to read it character by character and then print it ? If i use 'char' instead of 'string' to read the contents, then can i still use the 'vector' or is there any other key word ? – user2917559 Feb 13 '14 at 22:38
  • please look at this also, http://stackoverflow.com/questions/21767700/c-pointer-to-integer-comparison-error – user2917559 Feb 13 '14 at 23:19
2

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

Sebastian Negraszus
  • 11,915
  • 7
  • 43
  • 70