在C ++中,如何读取文本文件的内容,然后将其放在另一个文本文件中? [英] In C++, how to read the contents of a text file, and put it in another text file?

查看:176
本文介绍了在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>

这篇关于在C ++中,如何读取文本文件的内容,然后将其放在另一个文本文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆