Sign in to follow this  
The Rug

string::compare not working as expected

Recommended Posts

Hi Gamedev, I'm currently writing a little multi-platform game using C++ and I've encountered a problem with parsing the text file that contains the level data.
std::string collidableType;
std::getline( input, collidableType ); // Input is a istream object

// Print the sresult of the string::compare operation
std::cout << "Collidable type: '" << collidableType << "'" << std::endl;
std::cout << "Compare collidableType to 'poly': " << collidableType.compare( "poly" ) << std::endl;
The line read from the file contains the word "poly." Console output: Collidable type: 'poly' Compare collidableType to 'poly': 1 Under windows, the value is 0, as expected. But compiled for my iPhone it's 1. If I initialise collidableType to "poly" rather than reading it from the istream, the result is 0 and it works. So I'm assuming it's to do with how the string is read from getline but I can't figure out what. Can anyone offer me some advice?

Share this post


Link to post
Share on other sites
Either the string contains something completely unprintable (check size()), or there is undefined behavior elsewhere in the program which happens to manifest itself by screwing up the comparison operation.

Share this post


Link to post
Share on other sites
It may be the way that lines are terminated in the text file. On Windows platforms, new lines are signaled in a text file with "\r\n" (Carriage Return + Line Feed). On other platforms, this is done with just Line-feed "\n". On your iPhone app, the extra "\r" character is not considered part of the "end-of-line" indicator, and is probably added to your string when you read a line, screwing up your comparison.

Share this post


Link to post
Share on other sites
Thanks guys, it was a carriage return '\r' that needed removing. I'm not sure why this makes the comparison equal to one though.

Anyhow, my solution (incase anyone else has this problem) was simply to remove any carriage returns from the string. This code did the trick:


collidableType.erase (std::remove (collidableType.begin(), collidableType.end(), '\r'), collidableType.end());

Share this post


Link to post
Share on other sites
Quote:
Original post by The Rug
Thanks guys, it was a carriage return '\r' that needed removing. I'm not sure why this makes the comparison equal to one though.


The compare method of an std::string returns the same results as strcmp, where these are:
0 = compare equal
<0 the first character that is not the same is lexically less
>0 opposite of <0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this