[英]input/output for a file in c++
#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();
}
我不确定我在这里做错了什么。 在这个程序中,我试图将输入的文件名转换为 cin,然后将 output 转换为您输入的文件名。
相同的fstream
object 被重用:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.