Reputation: 471
I am trying to compare two strings. Here is the code that I have.
string line;
getline(cin, line);
if(line.compare("% Input alphabet")==0)
dosomething;
The problem is the following code works correctly when using mingw on a windows machine but when I run the same code on my ubuntu vm it does not execute dosomething method. I compiled my program and ran the following commands
On windows
a.exe < input.txt
On Ubuntu
./a.out < input.txt
Upvotes: 0
Views: 307
Reputation: 6876
Are you using the exact same input.txt
file that you created on Windows and then transferred to the Linux machine? If you are, then this might cause the problem you describe.
The idea is that C++ streams treat the line ending character differently based on platform (if you don't open the stream in binary mode). This line of code:
someTextFileStream << "some text\n";
if run on Windows will actually write \r\n
at the end of the line and if run on Linux will only write \n
.
The same is true when reading from text streams, on Windows \r\n
will be interpreted as a single new line character/delimiter, on Linux only \n
will be interpreted as the new line character.
Now if you create a text file on Windows (with Notepad for example), it will look something like this:
some text written on Windows\r\n
If you use getline()
on Windows to read this, the string that getline()
fills will contain some text written on Windows
.
If you transfer this file exactly like this on Linux (so it is binary identical to the Windows file) and then read it using getline()
again, the string will actually contain some text written on Windows\r
. This is because on Linux the new line delimiter is \n
and so getline()
stops on that.
Possible solutions: trim the lines after reading them from the file; detect the line end delimiter and convert/handle it appropriately in your code; use proper line endings for the platform the code runs on when creating the file.
Upvotes: 0
Reputation: 6556
I'd suggest trimming \r\n
symbols at the end. That's the only difference between Window (\r\n) and Unix (\n).
Use boost::trim()
to do that
Upvotes: 2