2010-12-06 3 views
0

두 개의 개별 파일의 첫 번째 줄을 읽고이를 비교하려면 ... 다음 코드는 사용하지만 "문자열 오류에 대한 istream"을 제공합니다. while 조건을 사용하여 파일을 먼저 읽어야합니까?getline 및 파일 처리

ifstream data_real(filename.c_str()); /*input streams to check if the flight info 
            are the same*/ 
ifstream data_test("output_check.txt"); 
string read1, read2; 
string first_line_input = getline(is,read1); 
string first_line_output_test = getline(data_test,read2); 

string test_string1, test_string2; 
int num_lines_output_test, num_lines_input; 
if((first_line_input.substr(0,3)==first_line_output_test.substr(0,3))) 
{ 
    while(!data_test.eof()) // count the number of lines for the output test file with the first flight info 
    { 
     getline(data_test,test_string1); 
     num_lines_output_test++; 
    } 
    while(getline(is,test_string2)) // count the number of lines for the output test file with the first flight info 
    { 
     if(test_string2.substr(0,3)!="ACM") 
      num_lines_input++; 
     else 
      break; 
    } 
} 
+1

실제 오류 메시지를 복사하여 붙여 넣으십시오. –

답변

1

getline(istream, string)은 문자열이 아닌 istream에 대한 참조를 반환합니다. 또한

string read1, read2; 
if !(getline(is,read1) && getline(data_test,read2)){ 
    // Reading failed 
    // TODO: Handle and/or report error 
} 
else{ 
    if(read1.substr(0,3) == read2.substr(0,3)){ 
     //... 

:

그래서, 각 파일의 첫 줄을 비교하는 식으로 뭔가를 할 수있는 절대 사용 EOF() 스트림 읽기 루프 종료 조건으로. 를 작성하는 관용적 인 방법은 다음과 같습니다

std::string next_line(std::istream& is) { 
    std::string result; 
    if (!std::getline(is, result)) { 
    throw std::ios::failure("Failed to read a required line"); 
    } 
    return result; 
} 

지금 당신이 (즉, 문자열을 초기화 파일에서 원하는 방식으로 라인을 사용하기보다는 수정할 수 있습니다 :

while(getline(data_test,test_string1)) // count the number of lines for the output test file with the first flight info 
{ 
    num_lines_output_test++; 
} 
+0

그래서 두 파일의 첫 줄을 어떻게 비교합니까? – dawnoflife

+0

@dawnoflife : 답변에 예제를 추가했습니다. –

0

보십시오이 도우미 함수를 추가) :

string first_line_input = next_line(is); 
string first_line_output_test = next_line(data_test);