1

Happy New Year, everyone!

I have a text file that looks like this:

A|AAAAA|1|2
R|RAAAA
R|RAAAA

A|BBBBB|1|2
R|RBBBB
R|RBBBB

A|CCCCC|1|2 
R|RCCCC

The following code searches for the relevant text in the file based on the key and returns all the lines that belong to the key:

while( std::getline( ifs, line ) && line.find(search_string) != 0 );

if( line.find(search_string) != 0 )
{
    navData = "N/A" ;
}

else{

    navData = line + '\n' ; // result initially contains the first line

    // now keep reading line by line till we get an empty line or eof
    while( std::getline( ifs, line ) && !line.empty() )
    {
        navData += line + '\n';
    }
}

ifs.close();
return navData;

In Windows I get what I need:

A|BBBBB|1|2
R|RBBBB
R|RBBBB

In Mac, however, code "&& !line.empty()" seems to get ignored, since I get the following:

A|BBBBB|1|2
R|RBBBB
R|RBBBB

A|CCCCC|1|2
R|RCCCC

Does anyone know why?

Cheers, everyone!

Igor Tupitsyn
  • 1,193
  • 3
  • 18
  • 45

1 Answers1

4

Windows and Mac have different opinions about how an empty line looks like. On Windows, lines are teminated by "\r\n". On Mac, lines are terminated by "\n" and the preceding "\r" leads to the line not being empty.

Oswald
  • 31,254
  • 3
  • 43
  • 68
  • For reference, this is one big reason there's an `ios_base::binary` flag. With an output stream in binary mode, what you write is what gets written; in text mode (the default), line endings may be translated so that (for example) `\n` becomes `\r\n`. *nix typically doesn't treat the two differently, but Windows typically will. (Your text editor will often let you specify the line terminator as well, for similar reasons.) – cHao Jan 01 '14 at 21:42
  • OK. So how should I solve my problem with that taken into consideration? Thanks! – Igor Tupitsyn Jan 01 '14 at 22:00
  • So you want to be [using `getline()` with multiple types of end of line characters](http://stackoverflow.com/questions/13995971/using-get-line-with-multiple-types-of-end-of-line-characters)? I'm sure that now that you know where the problem is, you will find a solution. – Oswald Jan 01 '14 at 22:09
  • Oswald, Thanks a lot! The function safeGetline found in one of your links did the trick! Much appreciated! – Igor Tupitsyn Jan 02 '14 at 04:28