#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// Main Routine
void main() {
char in;
string s,m;
fstream f;
// Open file
cout << "Positive Filter Program\n"<< endl;
cout << "Input file name: ";
cin >> s;
cout << "Output file name: ";
cin >> m;
f.open(s.data(),ios::in);
f.open(m.data(),ios::out);
// Loop through file
if(f.is_open())
{
while(f.good())
{
f.get(in);
f<<in;
cout << "\nFinished!"<< endl;
}
}
else cout << "Could not open file";
// Close file
f.close();
}
我不确定我在这里做错了什么。在这个程序中,我试图查看将输入的文件名,然后输出到您键入的文件名。
答案 0 :(得分:3)
正在重用相同的fstream
对象:
f.open(s.data(),ios::in);
f.open(m.data(),ios::out);
它永远不会读取输入文件。改为:
std::ifstream in(s.data());
std::ofstream out(m.data());
while
循环不正确,应在读取后立即检查读取尝试的结果:
char ch;
while(in.get(ch))
{
out << ch;
}
cout << "\nFinished!"<< endl; // Moved this to outside the while