2013-08-16 2 views
0

이 코드를 작성하는 데 문제가 있습니다. 컴파일을 작성했습니다. 이 코드는 두 개의 텍스트 파일을 통해 읽은 다음이 두 파일 내에 줄을 출력합니다. 그런 다음 두 파일을 넣고 결합 할 수 있지만 첫 번째 줄에는 file1 텍스트, 그 다음 줄에는 file2 텍스트가 있어야합니다. 모든두 개의 텍스트 파일을 읽은 다음 결합하여

#include <iostream> 
#include <fstream> 
#include <cmath> 
#include <string> 
using namespace std; 


int main() 

{ 

std::ifstream file1("file1.txt"); 
std::ifstream file2("file2.txt"); 
//std::ofstream combinedfile("combinedfile.txt"); 
//combinedfile << file1.rdbuf() << file2.rdbuf(); 


char filename[400]; 
string line; 
string line2; 

cout << "Enter name of file 1(including .txt): "; 
cin >> filename; 

file1.open(filename); 
cout << "Enter name of file 2 (including .txt): "; 
cin >> filename; 

file2.open(filename); 

    if (file1.is_open()) 
    { 
    while (file1.good()) 
    { 
     getline (filename,line); 
     cout << line << endl; 

    } 
    file1.close(); 
    } 

    else cout << "Unable to open file"; 

return 0; 
} 
if (file2.is_open()) 
    { 
    while (file2.good()) 
    { 
     getline (filename,line); 
     cout << line << endl; 
    } 
    file2.close(); 
    } 

    else cout << "Unable to open file"; 

    return 0;} 
+0

컴파일러는 무엇을 말합니까? – HAL

답변

1

첫째, 예상대로 while (file.good()) 또는 while (!file.eof()), 그것은 작동하지 않습니다하지 않습니다

여기 내 코드입니다. 대신 예 : while (std::getline(...)).

  1. std::vector 객체로 파일을 모두 읽고,이 벡터에서 인쇄 :

    읽고 다른 라인을 인쇄하려면

    , 두 가지를 할 수있는 방법이 있습니다. 또는 두 벡터를 하나의 벡터로 결합하여 인쇄하십시오.
  2. 첫 번째 파일에서 한 줄을 읽고 인쇄 한 다음 두 번째 파일에서 읽고 루프에 인쇄하십시오.

첫 번째 대안은 가장 쉽지만 메모리를 가장 많이 사용합니다. 두 번째 대안을

, 당신은 이런 식으로 뭔가를 할 수 : 단순히

std::ifstream file1("file1.txt"); 
std::ifstream file2("file2.txt"); 

if (!file1 || !file2) 
{ 
    std::cout << "Error opening file " << (file1 ? 2 : 1) << ": " << strerror(errno) << '\n'; 
    return 1; 
} 

do 
{ 
    std::string line; 

    if (std::getline(file1, line)) 
     std::cout << line; 

    if (std::getline(file2, line)) 
     std::cout << line; 

} while (file1 || file2); 
0

또는를 :

cout << ifstream(filename1, ios::in | ios::binary).rdbuf(); 
cout << ifstream(filename2, ios::in | ios::binary).rdbuf(); 
0

두 번째 경우 문은 주()의 외부 - 기능. 첫 번째 반환 후 0; 당신은 main() 함수를 닫습니다. 코드의 또 다른 문제점은 return() 함수가 main() 함수에 있기 때문에 두 번째 if-Statement에 도달하지 않는다는 것입니다. 메인()을 끝냅니다. 첫 번째 파일 스트림이 "불량"인 경우 반환을 실행하고 싶으므로 else에 대한 범위가 필요합니다.

관련 문제