反向堆叠到文件中

Reverse stack into file

本文关键字:文件      更新时间:2023-10-16

我需要创建一个程序来读取文件,将内容推送到堆栈中,然后将该内容反向写入另一个文件。我不明白为什么找不到或输出我的文件。这是我的代码:

#include "stdafx.h"
#include <iostream>
#include <stack>
#include <fstream>
#include <string>

int main() {
std::stack<char>charStack;
std::fstream file;
std::fstream revFile;
std::string fileName;
std::cout << "Enter the name of the file you want to open." << std::endl;
std::cin >> fileName;
file.open(fileName);
std::cout << "Adding input from file to stack." << std::endl;
char ch;
file >> std::noskipws;
while (file >> ch) {
    std::cout << ch;
    charStack.push(ch);
}
file.close();
revFile.open("newFile.txt");
std::cout << std::endl;
std::cout << "Reversing stack and writing to file." << std::endl;
while (!charStack.empty()) {
    char i = charStack.top();
    revFile << i;
    charStack.pop();
}
revFile.close();
revFile.open("newFile.txt");
std::cout << "Here is the original file reversed." << std::endl;
std::string line;
    if (revFile.is_open()) {
            while (std::getline(revFile, line)) {
                    std::cout << line;
            }
            revFile.close();
    }
    else std::cout << "Unable to open file" << std::endl;

revFile.close();
return 0;
}

不确定我是否需要添加一个空的.txt文件来写入,或者这是否应该为我生成一个。任何帮助将不胜感激。

您需要将文件打开语句更改为:

revFile.open("newFile.txt",ios::out); //for output

revFile.open("newFile.txt",ios::in); //for input

除此之外,您只需要更正此行即可在反转后正确打印文件内容。

  std::cout << line;

来得及:

  std::cout << line << "n";