문제

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

string s = "word";
string p1 = s + s[s.size() - 1] == 's' ? "" : "s";

means:

if(s + s[s.size() - 1] == 's')
{
    p1 = "";
}
else
{
    p1 = "s";
}

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 character s

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:

if(s[s.size() - 1] == 's') // compare the last character
{
    p1 = s + ""; // equivalently = s but for clarity in the next step we'll write it like this
}
else
{
    p1 = s + "s"; // append the s
}

So now we can condense this back down, adding in brackets to get the desired behaviour

string p1 = s + (s[s.size() - 1] == 's' ? "" : "s");

We append something to s, where the something is determined by the last character of s

다른 팁

I assume you want something like this:

string p1 = s + ((s[s.size() - 1] == 's')? "" : "s");

You want something like:

string s = "word";
string p1 = s + ((s[s.size() - 1] == 's')? "" : "s");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top