【问题标题】:I/O file stream C++I/O 文件流 C++
【发布时间】:2023-03-08 08:31:02
【问题描述】:
#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;
}

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

【问题讨论】:

  • 你用过调试器吗?它是否输出您的“数据传输完成”消息?
  • 您是否尝试过刷新输出文件?
  • 每次迭代调用 getline 两次(第一次检查 (temp != ""),第二次写入 outfile)是故意的吗?
  • 如果我们知道 (a) 您的程序 应该 做什么,(b) 什么输入数据的样子,以及 (c) 为什么您认为您的代码应该可以工作,但 似乎没有
  • 这可能不是你的直接问题,但你不应该在循环条件中使用.eof()。这样做几乎总是会导致程序出错。

标签: c++


【解决方案1】:

你想复制每一行吗?

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

【讨论】:

    【解决方案2】:

    你应该使用一种模式来打开文件:见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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      • 2015-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多