std::getline() with files.

OK, so I've never had this problem before, ever. I have no idea why it's doing it now.

I haven't coded for a long while, so maybe something changed? lol. I am now using VS Ultimate 2012, maybe it's that?

So, anyway. On to the problem. I'm reading from a file and populating two vectors. See the std::getline() calls within the while-loop below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//Populate vectors

#include "Header.h"

bool populateVectors( stVector &c, stVector &m )
{
	//Create an ifstream.
	std::ifstream iFile;
	iFile.open( "ttmc.dat", std::ios::binary );

	//Create a std::string to hold file data
	std::string input;

	if( iFile.is_open() )
	{
		//Ignore the first line in the file.
		std::getline( iFile, input, '\n' );

		//While it's not the end of file, grab data.
		while( iFile.good() )
		{
			//Get data from file. Up until the [tab] ( Character )
			std::getline( iFile, input, '\t' );

			//Save the character.
			c.push_back( input );

			//Get data from file. Up until the [newline] ( Morse code )
			std::getline( iFile, input, '\n' );

			//Save the morse code.
			m.push_back( input );
		}

		//Close the file after use.
		iFile.close();

		//Return true, on population completion.
		return true;
	}
	else
	{
		std::cout << "\tError opening file to populate the vectors.\n";
		return false;
	}
}


Sample file of input:
First line.
A	.-
B	-...
C	-.-.
D	-..


So, on line 29, std::getline( iFile, input, '\n' );.
When I look at the result of this, I get the following from each vector index:
.-\r
-...\r
-.-.\r
-..\r


Is there a way to stop this behavior? Or a work around to stop this '\r' appearing? '\n' used to be fine and I'd never even seen '\r' in file use before. Can someone please help with this.

Thanks!
Last edited on
windows saves line feed as \r\n
Yeah, I read that earlier while searching for it. But I have old programs that I've written and this problem doesn't occur.

Is there a way to use std::getline() with an escape sequence that will remove both of these?

Thanks for the reply.
Windows use \r\n to mark a new line. When reading a file in text mode (default) it will automatically convert \r\n to \n. In binary mode it will read the file as it is, without converting anything, so that is why you get the \r.
Last edited on
Oh wow... lmao. I just checked my other programs and not anywhere in them do I have std::ios::binary... ahaha.

Thanks Peter! Very much appreciated.


Edit:
For anyone else that happens to come across this error. The problem was on line 9.
iFile.open( "ttmc.dat", std::ios::binary );

Removing the statement 'std::ios::binary' or changing for 'std::ifstream::in' will fix this.

Again, thanks Peter!! (:
Last edited on
Topic archived. No new replies allowed.