1

I've noticed there were some questions similar, but I couldn't find the right answer.

I'd like to compare two strings - first given by the user, second written in the external .txt file. I almost wouldn't notice the problem because under Windows everything works just fine, condition in if is true for some certain values, but in Linux it isn't (it's compiling, but doesn't give proper results). I thought maybe cin is adding some extra characters under Linux (like \n etc.) but size() on both strings is the same value, as it should be.

What should I change?

string firststr, secondstr;
fstream dFile;
dFile.open("dfile.txt", ios::in);
if(dFile.good())
{
while (!dFile.eof())
{    
dFile >> secondstr; //string from file 
}

cin >> firststr;

if(firststr==secondstr) cout <<"OK!";

OK! is displayed under Windows, not under Linux. I have also used getline(cin,firststr) - without success.

I need to have a code working both under Windows (which I have already) and Linux.

I hope fact that both strings are members of some class doesn't change anything.

Thanks in advance for any solutions.

  • 1
    See [this question](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) to learn why your loop is wrong. – molbdnilo Jan 12 '16 at 17:33

1 Answers1

1

If you copied the file from a Windows machine to a Linux machine, the file probably has CR+LF characters, it will cause problems when using that file on Linux.

Say the contents of the file are:

abcd<CR><LF>

When you run your code in Windows, it will pickup abcd as the last valid string in the file.

When you run your code in Linux with the same file, it will pickup an empty string as the last valid string in the file.

If you cleanup the file to contain

abcd<LF>

it will work fine on Linux.

Suggestion for further improvement:

Change the while loop to:

while (dFile >> secondstr)
{    
}

See Why is iostream::eof inside a loop condition considered wrong? for further details.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270