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

2024-03-29

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

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

在您的代码中,您没有存储输入行。首先,定义一个字符串向量

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

并将每个输入行存储到您的列表中

inputLines.push_back(line)

然后通过循环遍历向量的项目来将输入行写入输出

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

PS:你可能需要

#include <vector>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在C++中,如何读取一个文本文件的内容,并将其放入另一个文本文件中? 的相关文章

随机推荐