【问题标题】:Is strnlen function supported in C++, on codeblocks ide?在代码块 ide 上,C++ 是否支持 strnlen 函数?
【发布时间】:2015-09-20 06:09:29
【问题描述】:

我的程序是:

#include <cstdio>
#include <cstring>
using namespace std;

int main(int argc,char **argv)
{
    const static size_t maxbuf=128;
    const char * s1="String one";
    char sd1[maxbuf];
    printf("length is %ld",strnlen(sd1,maxbuf));
    return 0;
}

错误是:

 strnlen was not declared in this scope

问题:

  1. 为什么我无法在我的 codeblocks IDE 上使用 C++ 中的 strnlen 函数?

  2. 他们是strnlen 的好替代品吗?

【问题讨论】:

  • 你遇到了什么错误?
  • 检查 strnlen 函数的定义位置并包含该库。
  • 你为什么没有std::string-s?
  • strnlen() 是一个posix函数,cstring只提升标准C库函数。
  • 你为什么不使用std::stringstd::cout等?

标签: c++ c++11


【解决方案1】:

strnlen 是 GNU 扩展,也在POSIX (IEEE Std 1003.1-2008) 中指定。如果strnlen 不可用(在不支持此类扩展时可能发生),请使用以下替换。

// Use this if strnlen is missing.
size_t strnlen(const char *str, size_t max)
{
    const char *end = memchr (str, 0, max);
    return end ? (size_t)(end - str) : max;
}

我回答了类似的问题here

【讨论】:

  • 谢谢你,但你能建议我在没有这个实现的情况下 strnlen 在 Windows 中工作的编译器(或 IDE)吗?是否有类似的替代方案可以使其在代码块 ide 上工作?实际上,它在我的 Mac 中使用 xcode 完美运行,无需任何进一步的实现。
  • IDE != 编译器 != 链接器 != 库。这与编译器或 IDE 无关。仅仅因为它们有时是捆绑在一起的(例如 VS 附带编译器和链接器,...),这并不意味着它们是相同的。 IDE 只是您在其中编写源代码并可以设置构建链的环境 - 仅此而已。当您的平台上没有扩展程序时,您为什么不使用我发布的功能?
  • 一般的经验法则是尽可能依赖标准库。你在处理遗留代码吗?您是否需要处理 c 字符串而不是 std::string
猜你喜欢
  • 1970-01-01
  • 2011-05-19
  • 2014-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-20
  • 2014-03-03
相关资源
最近更新 更多