我需要创建一个程序来读取文件,将内容压入堆栈,然后将该内容反向写入另一个文件。我不明白为什么我的文件没有找到或输出。这是我的代码:
#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文件来写入,或者是否应该为我生成一个.txt文件。任何帮助将不胜感激。
答案 0 :(得分:1)
您需要将文件打开语句更改为:
revFile.open("newFile.txt",ios::out); //for output
和
revFile.open("newFile.txt",ios::in); //for input
除此之外,您只需更正此行即可在翻转后正确打印文件内容。
std::cout << line;
成功:
std::cout << line << "\n";