使用堆栈反转txt文档

Reversing a txt document using stacks

本文关键字:txt 文档 堆栈      更新时间:2023-10-16

好吧,我正在写一个相对简单的程序,它从txt文档中提取字符,将它们从堆栈中弹出并保存到第二个文件中,但顺序相反,例如:

你好!

ereht olleh

我有一些代码,我一直在调整它,但它执行不正确。

#include <iostream>
#include <fstream>
#include <string>
include <stack>
using namespace std;
void reverse(ifstream & infile, ofstream & outfile);  //function prototype
void main () 
{
ifstream infile;  // declaring a file for input
ofstream outfile; // declaring a file for output
infile.open ("myInputFile.txt"); 
 if (!infile) 
 { cout << "File could not be opened." << endl;
 }
 outfile.open ("myOutfile.txt");
 reverse (infile, outfile);
infile.close();// Close both files
outfile.close();

system("pause");
}
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 (getline(infile, s)) // while not end of file
 { 
     mystack.push(s);
     getline(infile, s); // try to read another line
 }
 while (!mystack.empty())
 {
     s = mystack.top();
     outfile << s << endl; // write s to the outfile
     mystack.pop();
 }

 }

编辑:对不起,我忘了最重要的部分。。问题。当程序执行时,它不会对输出文件执行任何操作。这让我相信这是我的逻辑中关于相反部分的部分。

编辑:编辑:好吧,我一直在胡搞,我仍然无法让它做什么,它现在打印到输出文件,但它只是把第2行的内容放在第1行。

示例:输入文件:

Hello world How are things

输出文件:How are things

我想要的输出要么是所有字符颠倒,要么只是单词顺序颠倒。

示例"dlrow olleh"或"世界你好">

很抱歉,这是我的第一篇帖子,但我正在努力寻求帮助。

提前谢谢!

感谢您的帮助@ooga。流行音乐让我走上了正轨,尽管这不是我的问题。

我意识到我使用的是字符串堆栈,而我本应该使用Char堆栈来做我想要的事情并获得我想要的输出。

程序现在运行良好。

-Titan