1
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
using namespace std;

int main() 
{

    string temp;

    ifstream inFile;
    ofstream outFile;

    inFile.open("ZRMK Matched - 010513.txt");
    outFile.open("second.txt");

    while(!inFile.eof()) {  

        getline(inFile, temp);
        if (temp != "") {
            getline(inFile, temp);
            outFile << temp;
        }
    }

    cout << "Data Transfer Finished" << endl;

    return 0;
}

我很难让这个工作。当我执行程序时,它会循环一段时间,然后在没有完成的情况下终止——它不会将任何文本行输出到输出文件。任何帮助,将不胜感激。

4

2 回答 2

5

你想复制每一行吗?

while(std::getline(inFile, temp)) {
  outFile << temp << "\n";
}

您是否要复制每个非空白行?

while(std::getline(inFile, temp)) {
  if(temp != "")
    outFile << temp << "\n";
}

您是否要复制每第二个非空白行?

int count = 0;
while(std::getline(inFile, temp)) {
  if(temp == "")
    continue;
  count++;
  if(count % 2)
    outFile << temp << "\n";
}

您只是想复制整个文件吗?

outFile << inFile.rdbuf();
于 2013-02-13T18:35:55.113 回答
0

您应该使用一种模式来打开文件:请参阅std::ios_base::openmode
并且不要忘记关闭您打开的流!
如果发生异常,您甚至可以尝试捕获您的代码以了解问题。

#include <string>
#include <fstream>
#include <iostream>

using namespace std;

int main() 
{
    try {
        fstream inFile;
        fstream outFile;

        // open to read
        inFile.open("ZRMK Matched - 010513.txt", ios_base::in); 
        if (!inFile.is_open()) {
            cerr << "inFile is not open ! " << endl;
            return EXIT_FAILURE;
        }

        // Open to append
        outFile.open("second.txt", ios_base::app); 
        if (!inFile.is_open()) {
            cerr << "inFile is not open ! " << endl;
            return EXIT_FAILURE;
        }

        string line;
        while(getline(inFile, line)) {  
            if (!line.empty()) {
                outFile << line << endl;
            }
        }

        if (outFile.is_open()) {
            outFile.close(); // Close the stream if it's open
        }
        if (inFile.is_open()) {
            inFile.close(); // Close the stream if open
        }

        cout << "Data Transfer Finished" << endl;
        return EXIT_SUCCESS;

    } catch (const exception& e) {
        cerr << "Exception occurred : " << e.what() << endl;
    }

    return EXIT_FAILURE;
}
于 2013-02-13T23:50:12.533 回答