+ 由于有条件,运算符不起作用
+ Operator does not work due to conditional
尝试
将变量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();
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++11+=当RHS有多个字符串或字符时,运算符不起作用
- C++ - 父级中的 CRTP 分配运算符不起作用
- 为什么重载运算符上的异常说明符'<<'不适用于任何 std::ostream 对象,但对库中定义的运算符不起作用?
- 为什么重载运算符不起作用?
- 重载运算符<<不起作用
- 构造函数和运算符不起作用
- 重载+运算符不起作用
- + 由于有条件,运算符不起作用
- 集合迭代器的加号运算符不起作用
- 重载运算符<<不起作用
- 取消引用运算符不起作用(语法问题?
- 为什么当bool = true时补码运算符不起作用?
- 为什么增量运算符不起作用?
- 插入和提取运算符不起作用
- "if"语句"or"运算符不起作用
- 具有继承的重载方法/运算符不起作用
- 使用 OSTREAM 重载<<运算符不起作用。为什么?
- 赋值运算符不起作用
- 继承的运算符 = 不起作用