0
   #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();

    }

I am not sure what I am doing wrong here. In this program I am trying to cin the file name that would input, and then would output onto what file name that you typed in.

4

1 回答 1

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
于 2012-04-10T10:32:53.690 回答