替换 C++ 的疑难解答

Troubleshooting replace c++

本文关键字:疑难解答 C++ 替换      更新时间:2023-10-16

我在C++有以下代码:

void main()
{
string line_1="1 | 2 | 3";
string line_2="4 | 5 | 6";
string line_3="7 | 8 | 9";
int choice;
cin>>choice;
switch (choice)
            {
            case 1:
                replace(line_1.begin(), line_1.end(), "1", "O");
                break;
            case 2:
                replace(line_1.begin(), line_1.end(), "2", "O");
                break;
            case 3:
                replace(line_1.begin(), line_1.end(), "3", "O");
                break;
            case 4:
                replace(line_2.begin(), line_2.end(), "4", "O");
                break;
            case 5:
                replace(line_2.begin(), line_2.end(), "5", "O");
                break;
            case 6:
                replace(line_2.begin(), line_2.end(), "6", "O");
                break;
            case 7:
                replace(line_3.begin(), line_3.end(), "7", "O");
                break;
            case 8:
                replace(line_3.begin(), line_3.end(), "8", "O");
                break;
            case 9:
                replace(line_3.begin(), line_3.end(), "9", "O");
                break;
            {
            default:
                break;
            }
            }
    }

它的作用是将上面给出的行更改为井字游戏的输入,在本例中为 O。但是当我运行此代码时,我收到以下三个错误:

ERROR C2446: '==': no conversion from 'const char' to 'int'
ERROR C2040: '==': 'int' differs in levels of indirection from 'const char[2]'
ERROR C2440: '=': cannot convert from 'const char[2]' to 'char'.

我的代码可能出现什么问题?

尝试:

replace(line_1.begin(), line_1.end(), '1', 'O');

尝试:

replace(line_1.begin(), line_1.end(), '1', 'O');
//                                    ^^^^^^^^^

建议你从 std::string 调用替换成员函数:

line_1.replace(line_1.begin(), line_1.end(), '1', 'O');