views:

238

answers:

2

Ok so I have a problem with getline.

I have a file that contains a couple strings. I created it by myself and I have each string on a seperate line.

Ex. textfile.txt
    Line 1
    Line 2
    Line 3
    Line 4

//Little snip of code
    ifstream inFile("textfile.txt");
    getline(inFile, string1);

When I debug the program and ask it to print out string1 it shows that "Line 1\r" is saved into string1. I understand that it's from me actually hitting enter when I created the file. This problem causes my program to have a segmentation fault. I know my code works because if I use ofstream to write the file first and then i read it in, it works.

So for my quesiton, is their anyway to use the getline function without it picking up the escape sequence \r? If i am not clear just let me know.

A: 

If your standard library is correctly implemented, the terminating character should be removed from the stream, but not appended to the string. Even if it was appended to the string, that shouldn't cause a segfault -- I think your problem lies elsewhere.

Jerry Coffin
+1  A: 

The fact that you have the '\r' character is unlikely to cause a seg fault by itself.

Other mysteries:
If you open a file for writing in binary the output is exactly what you output.
If you open a file for writing in text (the default) the output is the same except for '\n', which is transformed into a line termination sequence (more on that below).

If you open a file for reading in binary the input is exactly what is in the file.
If you open a file for reading in text (the default) the input is the same as the file except for the line termination sequence, which is transformed into the character '\n'.

In normal situations this is fine. But every platform seems to have its own definition of the line termination sequence. Thus if you write a text file on a MAC then read it on a PC it may not work as expected.

So unless you are doing one of the following everything should work.

  • Writing in Binary/Reading in Text
  • Writing in Text/Reading in Binary
  • Writing the file and OS1/Reading the file on OS2
    • Where OS1/OS2 do not have the same line termination sequence.

Note 1: If you write the file in Binary mode. You should not be using getline() which assumes text mode (it is expecting the line termination sequence to split lines). Sub Note: For the pedantic(s) out there the getline() may work on binary but this is probably relying on implementation details and you should not consider it portable.

Note 2: The above assumes you have not installed a specialized local that implements a facet that transforms stream data on the fly.

Martin York