问题描述
在我的代码中,在运行时我可以将 num 值设为零,因此想要添加条件,例如如果 num 值为零,则跳过其中一个子语句,否则添加到字符串语句中。
String Statement =
"Timer Main\r\n"
"Sharm \tv7 (" + IntToStr(Value) + ")\r\n"
"Get All Values \t" + FloatToStr((float)GetAllValues/50,1,2) + "\r\n"
"Sum of Values \t" + FloatToStr((float)SumOneValue/50,2,4) + "\r\n"
"% for \t" + FloatToStr(((float)num)*100.0,12,2) + "\r\n\r\n"
"--------------------------------\r\n"
解决方法
您可以使用字符串流:
#include <sstream>
...
std::stringstream s;
s << "Timer Main" << std::endl << "Sharm \tv7 (" << IntToString(value) << ")" << std::endl;
// ...
if (num == 0)
{
s << "";
}
else
{
s << "!= 0";
}
// ...
std::string statement = s.str();
这样做的好处是您可以分多个步骤创建字符串,因此条件检查更容易。您还可以使用 iomanip 提供的格式选项,例如填充空格等。
,条件运算符可用于编写紧凑:
bool condition = false;
std::string str = std::string("hello") + (condition ? std::string(" true string") : " false string") + " world";
std::cout << str;
输出:
hello false string world
不过,条件运算符也是编写不可读代码的好方法,您可能应该这样做:
std::string str2 = "hello";
if (condition) str2+= " true string";
else str2+= " false string";
str2+=" world";
不要试图将所有内容都压缩在一个语句中。