Hello, I am reaaly having trouble with getline, it seems that it is reading the eol '\r' character and storing it in the string. if the first line of test.txt is "abcd", I will get: str.size()=5 with the code bellow:
Is it influencing your strings? I doubt you'll be using str.size() for anything important, so if that's the only part "wrong", just ignore it.
Maybe try concatenating two strings (e.g. the first two lines) and see if there's any odd behaviour. It could be that it still counts the "zero-end" of a c-string, rather than the eol.
I am converting it afterward to a c_str() then saving it in binary file, so I need the length of the string to be correct.
Concateneting the strings is a brilliant idea, it shows something weird now.
If I add a string("new") at the beggining and cout it, I get:
newABCDE,
while if I add it at the end I only get
new
This is really making me trouble! I think the string is still keeping eol, event if I use the example from this website above!
Just so you know, std::getline( ) stops the read operation once the new-line character is found. Once a new-line character is found, it's extracted followed by a discard. So it's not possible for a new-line character to be within the string that stores the extracted content.
The getline() function is designed to read files based upon the current platform locale.
Newline sequence:
Windows Linux Mac
\r\n \n \r
If you are using a program under Linux but reading a file with a Windows newline sequence, you will get those '\r's at the end of the string.
The problem can be fixed in code, but that is the wrong thing to do (usually). Instead, you should properly transfer your text files so that they are converted to use the correct newline sequence.
If you have already transferred your text files using BINARY mode, you can still fix it. On Linux, there is a nice little utility called dos2unix. http://linux.die.net/man/1/dos2unix
Use it to fix your text files so that the newline sequence is correct.
mik2718 and Duoas, you are right
I didnt pay attantion, I was creating the text file from Windows, and running my stuff ona linux platform so I had this \r left each time...
I create now my files on linux directly so it solved the problem,