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 に答える