I am reading C++ Primer, 5th Edition to learn C++ however I have come across a question that I am kind of stuck at. The question is as follows:
The following expression fails to compute due to operator precedence. How would you fix it?
string s = "word"; string p1 = s + s[s.size() - 1] == 's' ? "" : "s";
I have tried various solutions but I can't seem to get it. My logic is that the equality operator needs two expressions so I need to create that but my solutions don't work.. Any help is much appreciated!
In general, you don't want to fit your solution in to one line, so lets break this up in to the indivdual parts so we can see why it doesn't work, what we want and how we would do that.
What it is at the moment
means:
What's wrong
It is now clear why this won't work, firstly we are comaring a string (
s + s[s.size() -1]
) to a characters
Also, looking at the result, I suspect that isn't what you want.
The Fix
Instead we want to append an 's' if the last character is not an s. So in long form:
So now we can condense this back down, adding in brackets to get the desired behaviour
We append something to
s
, where the something is determined by the last character ofs