Reputation: 1
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...
Upvotes: 0
Views: 37
Reputation: 598134
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] = ' ';
...
}
...
}
Upvotes: 1