在尝试将变量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;
}
答案 0 :(得分:1)
这是逻辑错误还是数据类型错误?
这是数据类型错误。 acidWeight
的类型为float
,operator+()
获取float
参数没有重载。
如果您想构建文本格式的字符串,就像使用例如std::cout
,您可以使用std::ostringstream
:
std::ostringstream oss;
oss << "The weight of " << acidName << "is " << acidWeight << "per mole";
answerString = oss.str();
答案 1 :(得分:0)
更正:我在错误的观念下工作,你不能在某些c ++标准中使用const char *作为运算符+()操作数和字符串。我已相应地改变了我的答案。
acidWeight是一个float,它没有运算符+()函数来允许与字符串连接。
因此,我猜你可能会说你导致数据类型错误,因为你试图使用一个对于预期数据类型不存在的函数(const char *)。
使用现代C ++,您应该使用<sstream>
中的字符串流来动态组合字符串。
e.g。
std::stringstream ss;
ss << "Hi" << " again" << someVariable << ".";
std::string myString = ss.str();
const char *anotherExample = myString.c_str();
答案 2 :(得分:0)
您也可以将float更改为string,因为您没有返回浮点值。你只想打印出来。
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;
}