在C ++中,如何读取文本文件的内容,然后将其放在另一个文本文件中?

问题描述:

我想读取input.txt文件的内容并将其放在output.txt文件中,我尝试在下面的代码中进行此操作,但是我没有成功,我是 C ++的新手文件操作,您能告诉我该怎么做吗?

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;
     }

在您的代码中,您没有存储输入行.首先,通过

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

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

,并使用

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:您可能需要

#include <vector>