#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;
}
我很难让这个工作。当我执行程序时,它会循环一段时间,然后在没有完成的情况下终止 - 它不会向输出文件输出任何文本行。任何帮助将不胜感激。
答案 0 :(得分: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();
答案 1 :(得分: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;
}