2010-12-06 9 views
0

私は2つの別々のファイルの最初の行を読み、それらを比較したいと思います...私が使用するコードは以下の通りですが、 "istream to string error"を与えます。最初にファイルを読み始める条件を使用する必要がありますか?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);