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;
所以,这是我的代码。
我想从给定的字符串中找到一个字符(来自用户的输入)。并替换为空白。
但是,显然,这不是我应该使用查找和替换的方式。
请以正确的方式教我...
您没有正确使用std::string::find()
的返回值。
std::string::find()
返回指定字符的index,如果找不到,则返回std::string::find()
(-1)。它不返回std::string::npos
,就像您的代码似乎认为的那样。
评估bool
语句时,将非零整数值视为true。这意味着如果在任何索引非0或根本找不到处找到if
,您的代码将尝试执行upperRowPiecesToPlay.replace()
。
但是没有letter
的重载将std::string::replace()
作为输入。如果不是std::string::replace()
,则需要给它赋予letter
返回的索引。
尝试以下方法:
find()