Whenever I am getting a line from a file by using the string getline() function, I seem to be getting an extra character. I am curious to know what exactly that character is. It recently caused me a bit of trouble trying to debug.

Let's say the file is like this:
abcd
efgh

and I use this code

getline(inf, line);
cout << line.length();

I seem to be getting the number of characters in the line + 1, so with this example the length is 5. My file has no spaces after the text.

#include <iostream>
#include <string>


int main()
{
	std::string str( "This is a string\r" );
	std::cout << "The length of str is " << str.length() << std::endl;


	// wait for a keypress
	getchar();
	return 0;
}

use this code and you will see the answer is 17, why is that?
the \r character is at the end of the line. and Unix and DOS format
text files uses this different formats to terminate a line. as I remember
unix files uses \r\n and dos only uses \n.
so that's why you get an difference.

You will get a extra single character or two depending on you're
computer platform or the operating system.

That explains a lot since I got this file from a UNIX system. I find it funny how I have been working with files a lot recently and this was the first time that I noticed it.

as I remember unix files uses \r\n and dos only uses \n.
so that's why you get an difference.

Your memory is a little fuzzy -- its just the opposite.
MS-Windows/MS-DOS: \r\n
*nix: \n
MAC: \r

You will get a extra single character or two depending on you're
computer platform or the operating system.

I don't get an extra character on MS-Windows. getline() does not append the line terminating character under that os. It might with *nix, I don't know.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.