C++如何读取文本文件并反转行以便从下到上读取

标签 c++

请帮助我是 C++ 的新手

使用堆栈实现

我应该阅读包含以下内容的示例文本文件:

text file
begining to end
return text

并返回一个文本文件:

return text
begining to end
test file

这是测试实现的示例代码:

#include <iostream>
#include <fstream>
#include <string>
#include "stack1.h"
using namespace std

void reverse (ifstream & infile, ofstream & outfile);  //function prototype

int main () {

ifstream infile;  // declaring a file for input
ofstream outfile; // declaring a file for output
infile.open ("c:\\myInputFile.txt");  

 if (!infile)  { cout << "File could not be opened.  Program terminated." << endl;
           return 1;    // terminates program
         }
 outfile.open ("c:\\myOutfile.txt");
 reverse (infile, outfile);
 infile.close();
outfile.close();
 return 0;
 }

void reverse (ifstream & infile, ofstream & outfile) {
 string s;
 stack<string> mystack;

 getline(infile, s); // try to read a line of text from the file
 while (!infile) { // while not end of file
  mystack.push(s);
  getline(infile, s); // try to read another line
  }
 while (! mystack.isEmpty() ) {
  s = mystack.pop();
  outfile << s << endl; // write s to the outfile
  }
 }

最佳答案

怎么样:

//open infile in and outfile out.
std::stack<std::string> lines;
std::string temp;
while(std::getline(in, temp)) lines.push(temp);
while(!lines.empty()) outfile << lines.pop() << std::endl;

不过我不确定您的问题到底是什么。

编辑:将 push_back()pop_back 分别更改为 push()pop() (因为这些是 std::stack 提供的)。

关于C++如何读取文本文件并反转行以便从下到上读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2308505/

相关文章:

c++ - 如何将文本文件中的数据插入结构数组

C++ 流得到 unget 不是 nop?

c++ - 将 nullptr 转换为 std::optional

c++ - 使用C++解析Xml文件

c++ - 根据模板参数启用模板 Ctor

c++ - 模拟套接字错误

c++ - 在 SYCL 中使用屏障

c++ - 在 VSCode 中包含 SFML 库 "SFML/Graphics.hpp no such file or directory"gcc

c++ - 什么时候抛出不同类型的异常有用?

c++ - 读取各种维度的txt文件作为k-means算法程序的输入