C++ 如果 'something' 不为空并且不是 "0.0.0.0"

标签 c++

谁能帮我写下面的代码?

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/

相关文章:

c++ - C++中各种类型的任意嵌套可迭代实现的求和函数

c++ - 使用从另一个具体类返回的 shared_ptr

c++ - 面向对象设计 : Multiple instances but Static Callbacks

C++:使用 cin.getline()

c++ - if 和 else 没有大括号

c++ - 在 GOP(图片组)结束处剪切 MPEG 2 视频的 C 代码

c++ - 这个使用标准库的非常简单的 C++ 程序不能用 GCC 编译

c++ - 我怎样才能使这个 Makefile 更通用?

c++ - 避免对模板化类方法进行隐式转换

c++ - 如何将 lambda 用于 std::find_if