微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在 C++ 中的 String 语句中添加条件

在我的代码中,在运行时我可以将 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";

不要试图将所有内容都压缩在一个语句中。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。