2013-02-13 2 views
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; 
} 

이 작업을 수행하는 데 어려움이 있습니다. 프로그램을 실행하면 잠시 동안 순환 한 다음 끝내지 않고 종료합니다. 출력 파일에 텍스트 행을 출력하지 않습니다. 어떤 도움을 주시면 감사하겠습니다.I/O 파일 스트림 C++

+0

디버거를 사용 해본 적이 있습니까? '데이터 전송 완료'메시지가 출력됩니까? – Chad

+0

출력 파일을 플러시하려고 했습니까? –

+1

반복적으로 getline을 두 번 호출한다는 사실이 있습니다 (처음에는'(temp! = "" ")'를 확인하고 두 번째는 outfile에 쓰려고합니다) 의도적입니까? – fvu

답변

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"; 
} 

전체 파일을 복사하려고합니까? std::ios_base::openmode
을보고 열고 스트림을 닫습니다 잊지 마세요 :

outFile << inFile.rdbuf(); 
0

당신은 파일을 열 수있는 모드를 사용한다!
예외가 발생한 경우 문제를 이해하기 위해 코드를 잡을 수도 있습니다.

#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; 
}