在C++中的String语句中添加条件



在我的代码中,在运行时,我可以将num值设置为零,所以如果num值为零,则需要添加条件,然后跳过其中一个子语句,否则添加字符串语句。

String Statement = 
"Timer Mainrn"
"Sharm                tv7 (" + IntToStr(Value) + ")rn"
"Get All Values     t" + FloatToStr((float)GetAllValues/50, 1, 2) + "rn"
"Sum of Values    t" + FloatToStr((float)SumOneValue/50, 2, 4) + "rn"
"% for     t" + FloatToStr(((float)num)*100.0, 12, 
2) + "rnrn"
"--------------------------------rn"

您可以使用字符串流:

#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";

简单地说,不要试图把所有的东西都塞进一句话里。

最新更新