谁能帮我写下面的代码?
if(pAdapter->GatewayList.IpAddress.String != "" && pAdapter->GatewayList.IpAddress.String != "0.0.0.0");
{
printf("\tGateway: \t%s\n", pAdapter->GatewayList.IpAddress.String);
}
这是错的吗?我是 C++ 的新手。我只想在 pAdapter->GatewayList.IpAddress.String
ISN'T NULL 且也不是“0.0.0.0”时打印结果。
谢谢!
最佳答案
这里有几个潜在的问题。
- NULL,又名 0,又名“空指针”,不是与空字符串
""
相同的东西。根据更大的上下文,您可能想要检查其中之一或两者。 - 比较 C 风格的字符串(最好将其视为小整数数组,这些小整数通常但不一定对应于某些文本编码中的代码点)与
==
或!=
被默默接受,但没有做你期望的事情;它比较数组的内存地址,而不是它们的内容。 C++ 中的“字符串文字”语法生成这些数组的匿名实例。 - C++
std::string
对象更像是高级语言中的一流字符串对象,并应用==
或!=
给他们确实比较他们的内容。并编写str == "literal"
等。does compare the contents of the string to the contents of the literal .但是,这些对象不能直接传递给printf
。
您没有告诉我们您拥有这两个中的哪一个(或者它是否又是其他东西,例如特定于应用程序的字符串类)所以我只是推测,但您可能想要
char const *gw_name = pAdapter->GatewayList.IpAddress.String;
if (gw_name // checks for NULL - remove if impossible
&& *gw_name // idiomatic shorthand check for "" - remove if impossible
&& strcmp(gw_name, "0.0.0.0")) // strcmp returns 0 if equal,
// 1 or -1 if unequal
printf("\tGateway:\t%s\n", gw_name);
或
std::string const &gw_name = pAdapter->GatewayList.IpAddress.String;
// gw_name cannot be NULL in this case
if (!gw_name.empty() && gw_name != "0.0.0.0")
printf("\tGateway\t%s\n", gw_name.c_str());
取决于 pAdapter->GatewayList.IpAddress.String
是 C 风格的字符串还是 std::string
。
关于C++ 如果 'something' 不为空并且不是 "0.0.0.0",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21241588/