[英]How do i find character (variable) from a string?
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()
返回指定字符的索引,如果未找到則返回std::string::npos
(-1)。 它不返回bool
,就像您的代碼似乎認為的那樣。
當對if
語句求值時,非零整數值被視為真。 這意味着您的代碼將嘗試執行upperRowPiecesToPlay.replace()
如果在0 以外的任何索引處找到該letter
,或者根本找不到該letter
。
但是沒有將letter
作為輸入的std::string::replace()
重載。 如果它不是npos
,您需要改為給它find()
返回的索引。
試試這個:
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] = ' ';
...
}
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.