c++ - 如何检查 char* p 是否到达 C 字符串的末尾?

标签 c++

template<class IntType>
IntType atoi_unsafe(const char* source)
{
    IntType result = IntType();
    while (source)
    {
        auto t = *source;
        result *= 10;
        result += (*source - 48);
        ++source;
    }
    return result;
}

main() 中我有:

char* number = "14256";
atoi_unsafe<unsigned>(number);

但条件 while (source) 似乎无法识别 source 已遍历整个 C 字符串。它应该如何正确检查字符串的结尾?

最佳答案

while(source) 在指针环绕到 0 之前为真,但在现代系统中可能会在此之前崩溃。您需要取消引用指针以找到空字节,while(*source)

我讨厌发表简短的回答

关于c++ - 如何检查 char* p 是否到达 C 字符串的末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6323993/

相关文章:

c++ - 你有没有通过使用 boost::pool 获得显着的 boost ?

c++ - 使用字符串 vector 进行插入排序

c++ - 如何在 Xcode 上为 C++ 安装 vinecopulib 库?

c++ - 断开/连接设备时 WM_DEVICECHANGE 出现两次

c++ - 具有 "placeholder"值的宏

c++ - 正则表达式不显示 IPv6 匹配的正确结果

c++ - 获取时间的毫秒部分

c++ - 从 CLI C++ 项目引用非托管 C++ 项目

c++ - 如何使用 Windows API 列出目录中的文件?

C++ STL : Why allocators don't increase memory footprint of containers?