0
cin >> letter >> position; //This is inside the main(). void moveLetter(char letter, int position) {` if (upperRowPiecesToPlay.find(letter)) { upperRowPiecesToPlay.replace(letter,1 , " "); switch(position) { case 1: if(p1 == '.' ) { p1 = letter; } break; 

So, this is my code.

I'd like to find a character(input from a user) from the given string. And replace it with empty space.

However, obviously this is not how I should use the find and replace.

Please teach me the right way...

1

1 Answer 1

1

You are not using the return value of std::string::find() correctly.

std::string::find() returns the index of the specified character, or std::string::npos (-1) if not found. It does not return a bool, like your code seems to think it does.

When an if statement is evaluated, a non-zero integer value is treated as true. Which means your code will try to execute upperRowPiecesToPlay.replace() if the letter is found at any index other than 0, or is not found at all.

But there is no overload of std::string::replace() that will take the letter as input. You need to instead give it the index that find() returns, if it is not npos.

Try this instead:

void moveLetter(char letter, int position) { std::string::size_type index = upperRowPiecesToPlay.find(letter); if (index != std::string::npos) { upperRowPiecesToPlay.replace(index, 1 , " "); // alternatively: // upperRowPiecesToPlay[index] = ' '; ... } ... } 
Sign up to request clarification or add additional context in comments.

3 Comments

alternative2: upperRowPiecesToPlay.at(index) = ' '
@DavidC.Rankin std::string::at() performs bounds checking, std::string::operator[] does not. The index in this example is already guaranteed to be in-bounds by the if (assuming upperRowPiecesToPlay is not being modified by other thread), so at() would just be wasted overhead. It would make sense to use at() only if the if is omitted.
Yes, true, that's why upperRowPiecesToPlay.at(upperRowPiecesToPlay.find(letter)) = ' ' would work in one-shot.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.