+ 由于有条件,运算符不起作用

+ Operator does not work due to conditional

本文关键字:运算符 不起作用 有条件      更新时间:2023-10-16
尝试

将变量acidWeight放入answerString时,+ 运算符不起作用。这是逻辑错误还是数据类型错误?

string byName() {
    string acidName;
    string answerString;
    float acidWeight;
    cout << "Give me the name of the acid and I'll give you the weight." << endl;
    getline(cin, acidName);
    cout << endl << endl;
    if (acidName == "valine") {
        acidWeight = 117.1469;
    }
    else {
        cout << "This doesn't appear to be valid." << endl;
    }
    answerString = "The weight of " + acidName + "is " + acidWeight + "per mole";
    return answerString;
}

这是逻辑错误还是数据类型错误?

这是一个数据类型错误。 acidWeight 属于 float 类型,并且采用float参数的operator+()没有重载。


如果您想像使用例如 std::cout,可以使用std::ostringstream

std::ostringstream oss;
oss << "The weight of " << acidName << "is " << acidWeight << "per mole";
answerString = oss.str();

您也可以将浮点数更改为字符串,因为您不会返回浮点值。你只想把它打印出来。

string byName() {
    string acidName;
    string answerString;
    string acidWeight; //changed from float to string
    cout << "Give me the name of the acid and I'll give you the weight." <<     endl;
    getline(cin, acidName);
    cout << endl << endl;
    if (acidName == "valine") {
        acidWeight = "117.1469"; //make this as string
    }
    else {
        cout << "This doesn't appear to be valid." << endl;
}
    answerString = "The weight of " + acidName + "is " + acidWeight + "per mole";
    return answerString;

}

更正

:我在一个错误的概念下工作,即在某些 c++ 标准中,您不能将 const char* 用作带有字符串的运算符+() 操作数。我已经相应地改变了我的答案。

acidWeight 是一个浮点数,它没有运算符+() 函数来允许与字符串连接。

因此,我想您可以说您正在导致数据类型错误,因为您正在尝试使用预期数据类型(const char *)不存在的函数。

使用新式C++,应使用<sstream>中的字符串流来动态撰写字符串。

例如

std::stringstream ss;
ss << "Hi" << " again" << someVariable << ".";
std::string myString = ss.str();
const char *anotherExample = myString.c_str();