if I have very simple part of code like:
string myvariable;
getline(cin, myvariable);
cout << myvariable.size();
and if I run that program locally it returns appropriate value (so exactly number of characters including spaces in the given string).
But if I upload that program to the programs evaluation system (sth like programming olympics or spoj.com) I get value of size() 1 too much.
For example if myvariable value is "test", then:
locally:
size() == 4
in evaluation system:
size() == 5
I tried .length() but the result is exactly the same. What is the reason for that? Thank you for your answers!
After the discussion in the comments, it is clear that the issue involves different line ending encodings from different operating systems. Windows uses \r\n
and Linux/Unix use \n
. The same content may be represented as
"Hello World!\n" // in a Linux file
or
"Hello World!\r\n" // in a Windows file
The method getline
by default uses \n
as delimiter on Linux/Unix, so it would yield a one greater size for the Windows file, including the unwanted character \r
, represented as hex value 0D
.
In order to fix this, you can either convert the line endings in your file, or trim the string after reading it in. For example:
string myvariable;
getline(cin, myvariable);
myvariable.erase(myvariable.find_last_not_of("\n\r") + 1);
See also How to trim an std::string? for more ways to trim a string for different types of whitespace.