开发者

getline and file handling

开发者 https://www.devze.com 2023-01-28 23:01 出处:网络
I want to read the first lines of 2 separate files and then compare them...the following is the code i use but it gives me \"istream to string error\". do i need to use a while condition to start read

I want to read the first lines of 2 separate files and then compare them...the following is the code i use but it gives me "istream to string error". do i need to use a while condition to start reading the files first?

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


getline(istream, string) returns a reference to the istream, not a string.

So, comparing the first line of each file could be something like:

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)){
       //...

Also: Never use eof() as a termination condition for a stream reading loop. The idiomatic way to write it is:

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


Try adding this helper function:

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

Now you can use lines from the file the way you want (i.e. to initialize strings, rather than modify them):

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

精彩评论

暂无评论...
验证码 换一张
取 消