对于将 const char 分配给 std::string 的这种代码不兼容类型的错误,我不断收到此错误

I keep getting this error for the this code incompatible type of assignment of const char to std::string

本文关键字:错误 类型 不兼容 代码 char const 分配 string std      更新时间:2023-10-16
if(gamble == "You Get A Raise"){
            int raise[]    {1,2,3,4,5,6,7,8,9,10}
            cout << "You get a "     raise[rand()%10] << " $ Raise" << endl;
            salary = salary + raise; 
}

我试图制作一个程序,挑选出一个数字 1-10,然后将其添加到您当前的薪水中

您实际上要存储加薪的索引:rand()%10以便显示然后将相同的加薪应用于工资。

int raise[]    {1,2,3,4,5,6,7,8,9,10};
int raiseIdx = rand()%10;
cout << "You get a "  <<  raise[raiseIdx] << " $ Raise" << endl;
salary = salary + raise[raiseIdx]; 

您的gamble变量应为std::string

std::string gamble = "You Get A Raise";

你忘了<<吗?

试试这个:

int raise[] = {1,2,3,4,5,6,7,8,9,10};
int raise_value = rand()%10;
cout << "You get a " << raise[raise_value] << " $ Raise" << endl;
salary += raise[raise_value]; 

您的字符串gamble也需要std::string

std::string gamble = "You Get A Raise";

下面是一个完整的示例:

int salary = 1000;
std::string gamble = "You Get A Raise";
int raise[] = {1,2,3,4,5,6,7,8,9,10};
if (std::strcmp(gamble.c_str(),"You Get A Raise") == 0) {
// or
// if (gamble.compare("You Get A Raise") == 0) {
    int raise_value = rand()%10;
    cout << "You get a " << raise[raise_value] << " $ Raise" << endl;
    salary += raise[raise_value]; 
    cout << "New salary is $" << salary << endl;
}